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

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

演示的示例代码:

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?

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


当前回答

还有一种方法可以返回构造函数,这样你就可以在工厂中返回可更新的类,像这样:

function MyObjectWithParam($rootScope, name) {
  this.$rootScope = $rootScope;
  this.name = name;
}
MyObjectWithParam.prototype.getText = function () {
  return this.name;
};

App.factory('MyObjectWithParam', function ($injector) {
  return function(name) { 
    return $injector.instantiate(MyObjectWithParam,{ name: name });
  };
}); 

你可以在控制器中做这个,它使用MyObjectWithParam:

var obj = new MyObjectWithParam("hello"),

完整的例子如下: http://plnkr.co/edit/GKnhIN?p=preview

这里是谷歌小组页面,讨论的地方: https://groups.google.com/forum/ !味精/角度/ 56 sdorweoqg / b8hdPskxZXsJ

其他回答

我是这样理解它们在设计模式上的区别的:

Service:返回一个类型,该类型将被更新以创建该类型的对象。如果使用Java类比,则Service返回Java类定义。

Factory:返回一个可以立即使用的具体对象。在Java类比中,工厂返回一个Java对象。

经常让人(包括我自己)困惑的部分是,当你在代码中注入Service或Factory时,它们可以以相同的方式使用,在这两种情况下,你在代码中得到的是一个可以立即调用的具体对象。这意味着在服务的情况下,angular会代表你在服务声明中调用“new”。我认为这是一个复杂的概念。

生活的例子

" Hello world "的例子

与工厂/服务/供应商:

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() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.
 
    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()];
}​

有一段时间我有这种困惑,我在这里尽我所能提供一个简单的解释。希望这对你有所帮助!

Angular .factory和Angular .service都用于初始化服务,工作方式相同。

唯一的区别是您想如何初始化您的服务。

两人都是单身人士


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

工厂

App.factory(<服务名>,<函数返回值>)

如果您希望从具有返回值的函数初始化服务,则必须使用此工厂方法。

e.g.

function myService() {
  //return what you want
  var service = {
    myfunc: function (param) { /* do stuff */ }
  }
  return service;
}

app.factory('myService', myService);

当注入这个服务时(比如你的控制器):

Angular会调用给定的函数(如myService())来返回对象 单例——只调用一次,存储,传递同一个对象。

服务

App.service(<服务名称>,<构造函数>)

如果希望从构造函数初始化服务(使用此关键字),则必须使用此service方法。

e.g.

function myService() {
  this.myfunc: function (param) { /* do stuff */ }
}

app.service('myService', myService);

当注入这个服务时(比如你的控制器):

Angular会新建给定的函数(如new myService())来返回该对象 单例——只调用一次,存储,传递同一个对象。

注意:如果你使用factory函数和<构造函数>,或者使用service函数和<函数和返回值>,它将不起作用。


示例- DEMOs

Angular服务vs工厂 Angular服务vs工厂(带路由)

You can understand the difference with this analogy - Consider the difference between a normal function that will return some value and constructor function that will get instantiated using new keyword.So creating factory is just similar to create normal function that will return some value(primitive or an object) whereas creating service is like creating constructor function(OO class) of which we can create instance using new keyword. The only thing to notice is here is that when we use Service method to create services it will automatically create instance of it using dependency injection mechanism supported by AngularJS

以下是主要的区别:

服务

语法:模块。service('serviceName',函数);

结果:当将serviceName声明为可注入参数时,你将得到传递给module.service的函数实例。

使用方法:可以通过简单地将()附加到注入的函数引用来共享有用的实用程序函数。也可以用injectedArg运行。调用(这个)或类似的方法。

工厂

语法:模块。factory('factoryName',函数);

结果:当将factoryName声明为一个可注入参数时,你将得到通过调用传递给module.factory的函数引用返回的值。

用法:可能用于返回一个'class'函数,然后可以重新创建实例。

也可以查看AngularJS的文档和类似的关于stackoverflow混淆服务和工厂的问题。

下面是使用服务和工厂的示例。阅读更多关于AngularJS服务vs工厂的内容。