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

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

演示的示例代码:

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?

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


当前回答

对于工厂,你实际上是在工厂内部创建一个对象并返回它。 对于该服务,您只有一个使用this关键字进行定义的标准函数 函数。 在提供程序中,你定义了一个$get,它可以用来获取返回的对象 数据。

其他回答

所有angular服务都是单例:

文档(请参阅服务为单例):https://docs.angularjs.org/guide/services

最后,重要的是要认识到所有Angular服务都是应用程序单例。这意味着每个注入器只有一个给定服务的实例。

基本上,服务和工厂的区别如下:

app.service('myService', function() {

  // service is just a constructor function
  // that will be called with 'new'

  this.sayHello = function(name) {
     return "Hi " + name + "!";
  };
});

app.factory('myFactory', function() {

  // factory returns an object
  // you can run some code before

  return {
    sayHello : function(name) {
      return "Hi " + name + "!";
    }
  }
});

查看关于$ provider的演示:http://slides.wesalvaro.com/20121113/#/

这些幻灯片被用于AngularJs的一个聚会:http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html

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

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

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

对于工厂,你实际上是在工厂内部创建一个对象并返回它。 对于该服务,您只有一个使用this关键字进行定义的标准函数 函数。 在提供程序中,你定义了一个$get,它可以用来获取返回的对象 数据。

所有提供者都以相同的方式工作。不同的方法服务、工厂、提供者只是让你用更少的代码完成同样的事情。

附注:还有价值和常数。

从提供者开始到价值结束的链条上的每个特殊情况都有一个附加的限制。所以要在两者之间做出选择,你必须问问自己,哪一个能让你用更少的代码完成你想要的。

下面这张图可以说明我的意思:

你可以在我的博客文章中找到这张照片的分类和参考指南:

http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/