根据我的理解,当我在工厂中返回一个被注入到控制器的对象。当在服务中,我使用这个处理对象,不返回任何东西。

我假设服务总是单例的,并且每个控制器中都会注入一个新的工厂对象。然而,正如事实证明的那样,工厂对象也是单例的吗?

演示的示例代码:

var factories = angular.module('app.factories', []);
var app = angular.module('app',  ['ngResource', 'app.factories']);

factories.factory('User', function () {
  return {
    first: 'John',
    last: 'Doe'
  };
});

app.controller('ACtrl', function($scope, User) {
  $scope.user = User;
});

app.controller('BCtrl', function($scope, User) {
  $scope.user = User;
});

更改用户时。首先在ACtrl中,结果是那个用户。BCtrl中的first也改变了,例如User is a singleton?

我的假设是一个新的实例被注入到一个带有工厂的控制器中?


当前回答

服务样式:(可能是最简单的一种)返回实际函数:用于共享实用程序函数,只需将()附加到注入的函数引用即可调用。

AngularJS中的服务是一个单例JavaScript对象,它包含一组函数

var myModule = angular.module("myModule", []);

myModule.value  ("myValue"  , "12345");

function MyService(myValue) {
    this.doIt = function() {
        console.log("done: " + myValue;
    }
}

myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {

    myService.doIt();

});

工厂样式(更复杂但更复杂)返回函数的返回值:在java中实例化一个对象,如new object()。

工厂是一个创造价值的函数。当服务、控制器等需要从工厂注入价值时,工厂会按需创造价值。一旦创建,该值将被所有需要注入的服务、控制器等重用。

var myModule = angular.module("myModule", []);

myModule.value("numberValue", 999);

myModule.factory("myFactory", function(numberValue) {
    return "a value: " + numberValue;
})  
myModule.controller("MyController", function($scope, myFactory) {

    console.log(myFactory);

});

提供者样式:(完整的、可配置的版本)返回函数的$get函数的输出:可配置。

AngularJS中的Providers是你能创建的最灵活的工厂形式。向模块注册提供者就像向服务或工厂注册一样,只是使用了provider()函数。

var myModule = angular.module("myModule", []);

myModule.provider("mySecondService", function() {
    var provider = {};
    var config   = { configParam : "default" };

    provider.doConfig = function(configParam) {
        config.configParam = configParam;
    }

    provider.$get = function() {
        var service = {};

        service.doService = function() {
            console.log("mySecondService: " + config.configParam);
        }

        return service;
    }

    return provider;
});

myModule.config( function( mySecondServiceProvider ) {
    mySecondServiceProvider.doConfig("new config param");
});

myModule.controller("MyController", function($scope, mySecondService) {

    $scope.whenButtonClicked = function() {
        mySecondService.doIt();
    }

});

斯库尔克·延科夫

<!DOCTYPE html> <html ng-app="app"> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body ng-controller="MyCtrl"> {{serviceOutput}} <br/><br/> {{factoryOutput}} <br/><br/> {{providerOutput}} <script> var app = angular.module( 'app', [] ); var MyFunc = function() { this.name = "default name"; this.$get = function() { this.name = "new name" return "Hello from MyFunc.$get(). this.name = " + this.name; }; return "Hello from MyFunc(). this.name = " + this.name; }; // returns the actual function app.service( 'myService', MyFunc ); // returns the function's return value app.factory( 'myFactory', MyFunc ); // returns the output of the function's $get function app.provider( 'myProv', MyFunc ); function MyCtrl( $scope, myService, myFactory, myProv ) { $scope.serviceOutput = "myService = " + myService; $scope.factoryOutput = "myFactory = " + myFactory; $scope.providerOutput = "myProvider = " + myProv; } </script> </body> </html>

jsbin

<!DOCTYPE html> <html ng-app="myApp"> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <div ng-controller="MyCtrl"> {{hellos}} </div> <script> var myApp = angular.module('myApp', []); //service style, probably the simplest one myApp.service('helloWorldFromService', function() { this.sayHello = function() { return "Hello, World!" }; }); //factory style, more involved but more sophisticated myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!" } }; }); //provider style, full blown, configurable version myApp.provider('helloWorld', function() { this.name = 'Default'; this.$get = function() { var name = this.name; return { sayHello: function() { return "Hello, " + name + "!" } } }; this.setName = function(name) { this.name = name; }; }); //hey, we can configure a provider! myApp.config(function(helloWorldProvider){ helloWorldProvider.setName('World'); }); function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) { $scope.hellos = [ helloWorld.sayHello(), helloWorldFromFactory.sayHello(), helloWorldFromService.sayHello()]; } </script> </body> </html>

斯菲德尔

其他回答

基本的区别在于,提供程序允许将原语(非对象)、数组或回调函数的值设置到工厂声明的变量中,因此如果返回一个对象,它必须显式地声明和返回。

另一方面,服务只能用于将服务声明的变量设置为对象,因此可以避免显式地创建和返回对象,而另一方面,它允许使用this关键字。

或者简而言之,“提供者是一种更通用的形式,而服务仅限于对象”。

这里有更多的服务与工厂的例子,这些例子可能有助于了解它们之间的区别。基本上,一个服务调用了“new…”,它已经被实例化了。工厂不会自动实例化。

基本的例子

返回一个只有一个方法的类对象

下面是一个只有一个方法的服务:

angular.service('Hello', function () {
  this.sayHello = function () { /* ... */ };
});

下面是一个工厂,它返回一个带有方法的对象:

angular.factory('ClassFactory', function () {
  return {
    sayHello: function () { /* ... */ }
  };
});

返回一个值

返回数字列表的工厂:

angular.factory('NumberListFactory', function () {
  return [1, 2, 3, 4, 5];
});

console.log(NumberListFactory);

一个返回数字列表的服务:

angular.service('NumberLister', function () {
  this.numbers = [1, 2, 3, 4, 5];
});

console.log(NumberLister.numbers);

这两种情况下的输出是相同的,都是数字列表。

先进的例子

使用工厂“分类”变量

在这个例子中,我们定义了一个CounterFactory,它增加或减少一个计数器,你可以得到当前的计数或已经创建了多少个CounterFactory对象:

angular.factory('CounterFactory', function () {
  var number_of_counter_factories = 0; // class variable

  return function () {
    var count = 0; // instance variable
    number_of_counter_factories += 1; // increment the class variable

    // this method accesses the class variable
    this.getNumberOfCounterFactories = function () {
      return number_of_counter_factories;
    };

    this.inc = function () {
      count += 1;
    };
    this.dec = function () {
      count -= 1;
    };
    this.getCount = function () {
      return count;
    };
  }

})

我们使用CounterFactory创建多个计数器。我们可以访问class变量来查看创建了多少个计数器:

var people_counter;
var places_counter;

people_counter = new CounterFactory();
console.log('people', people_counter.getCount());
people_counter.inc();
console.log('people', people_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());

places_counter = new CounterFactory();
console.log('places', places_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());
console.log('counters', places_counter.getNumberOfCounterFactories());

这段代码的输出是:

people 0
people 1
counters 1
places 0
counters 2
counters 2

服务样式:(可能是最简单的一种)返回实际函数:用于共享实用程序函数,只需将()附加到注入的函数引用即可调用。

AngularJS中的服务是一个单例JavaScript对象,它包含一组函数

var myModule = angular.module("myModule", []);

myModule.value  ("myValue"  , "12345");

function MyService(myValue) {
    this.doIt = function() {
        console.log("done: " + myValue;
    }
}

myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {

    myService.doIt();

});

工厂样式(更复杂但更复杂)返回函数的返回值:在java中实例化一个对象,如new object()。

工厂是一个创造价值的函数。当服务、控制器等需要从工厂注入价值时,工厂会按需创造价值。一旦创建,该值将被所有需要注入的服务、控制器等重用。

var myModule = angular.module("myModule", []);

myModule.value("numberValue", 999);

myModule.factory("myFactory", function(numberValue) {
    return "a value: " + numberValue;
})  
myModule.controller("MyController", function($scope, myFactory) {

    console.log(myFactory);

});

提供者样式:(完整的、可配置的版本)返回函数的$get函数的输出:可配置。

AngularJS中的Providers是你能创建的最灵活的工厂形式。向模块注册提供者就像向服务或工厂注册一样,只是使用了provider()函数。

var myModule = angular.module("myModule", []);

myModule.provider("mySecondService", function() {
    var provider = {};
    var config   = { configParam : "default" };

    provider.doConfig = function(configParam) {
        config.configParam = configParam;
    }

    provider.$get = function() {
        var service = {};

        service.doService = function() {
            console.log("mySecondService: " + config.configParam);
        }

        return service;
    }

    return provider;
});

myModule.config( function( mySecondServiceProvider ) {
    mySecondServiceProvider.doConfig("new config param");
});

myModule.controller("MyController", function($scope, mySecondService) {

    $scope.whenButtonClicked = function() {
        mySecondService.doIt();
    }

});

斯库尔克·延科夫

<!DOCTYPE html> <html ng-app="app"> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body ng-controller="MyCtrl"> {{serviceOutput}} <br/><br/> {{factoryOutput}} <br/><br/> {{providerOutput}} <script> var app = angular.module( 'app', [] ); var MyFunc = function() { this.name = "default name"; this.$get = function() { this.name = "new name" return "Hello from MyFunc.$get(). this.name = " + this.name; }; return "Hello from MyFunc(). this.name = " + this.name; }; // returns the actual function app.service( 'myService', MyFunc ); // returns the function's return value app.factory( 'myFactory', MyFunc ); // returns the output of the function's $get function app.provider( 'myProv', MyFunc ); function MyCtrl( $scope, myService, myFactory, myProv ) { $scope.serviceOutput = "myService = " + myService; $scope.factoryOutput = "myFactory = " + myFactory; $scope.providerOutput = "myProvider = " + myProv; } </script> </body> </html>

jsbin

<!DOCTYPE html> <html ng-app="myApp"> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <div ng-controller="MyCtrl"> {{hellos}} </div> <script> var myApp = angular.module('myApp', []); //service style, probably the simplest one myApp.service('helloWorldFromService', function() { this.sayHello = function() { return "Hello, World!" }; }); //factory style, more involved but more sophisticated myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!" } }; }); //provider style, full blown, configurable version myApp.provider('helloWorld', function() { this.name = 'Default'; this.$get = function() { var name = this.name; return { sayHello: function() { return "Hello, " + name + "!" } } }; this.setName = function(name) { this.name = name; }; }); //hey, we can configure a provider! myApp.config(function(helloWorldProvider){ helloWorldProvider.setName('World'); }); function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) { $scope.hellos = [ helloWorld.sayHello(), helloWorldFromFactory.sayHello(), helloWorldFromService.sayHello()]; } </script> </body> </html>

斯菲德尔

对我来说,当我意识到它们都以相同的方式工作时,我得到了启示:通过运行一次,存储它们得到的值,然后在通过依赖注入引用时吐出相同的存储值。

假设我们有:

app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);

这三者的区别在于:

A的存储值来自运行fn,换句话说:fn() B的存储值来自于new fn,换句话说:new fn() C的存储值来自于首先通过new fn获得一个实例,然后运行实例的$get方法

这意味着,在angular内部有一个类似缓存对象的东西,它的每次注入的值只被赋值一次,当它们第一次被注入时,并且在:

cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()

这就是为什么我们在服务中使用This,并定义一个This。$get在供应商。

补充第一个答案,我认为.service()适合那些以更面向对象的风格(c# /Java)编写代码的人(使用这个关键字并通过prototype/Constructor函数实例化对象)。

Factory是为那些编写更自然的javascript/函数式代码的开发人员准备的。

看看angular.js中.service和.factory方法的源代码——在内部它们都调用provider方法:

  function provider(name, provider_) {
    if (isFunction(provider_)) {
      provider_ = providerInjector.instantiate(provider_);
    }
    if (!provider_.$get) {
      throw Error('Provider ' + name + ' must define $get factory method.');
    }
    return providerCache[name + providerSuffix] = provider_;
  }

  function factory(name, factoryFn) { \
    return provider(name, { $get: factoryFn }); 
  }

  function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
  }