对服务与工厂的困惑 [英] Confused about Service vs Factory
问题描述
据我所知,在工厂内部时,我返回一个注入控制器的对象.在服务内部时,我使用 this
处理对象并且不返回任何内容.
As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this
and not returning anything.
我假设服务总是单例,并且新工厂对象被注入到每个控制器中.然而,事实证明,工厂对象也是单例对象吗?
I was under the assumption that a service was always a singleton, and that a new factory object gets injected in every controller. However, as it turns out, a factory object is a singleton too?
示例代码演示:
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
中的user.first
时,结果是BCtrl
中的user.first
也被改变了,例如User
是单例?
When changing user.first
in ACtrl
it turns out that user.first
in BCtrl
is also changed, e.g. User
is a singleton?
我的假设是一个新实例被注入到带有工厂的控制器中?
My assumption was that a new instance was injected in a controller with a factory?
推荐答案
所有 Angular 服务都是单例:
文档(参见作为单例的服务):https://docs.angularjs.org/guide/services
最后,重要的是要意识到所有 Angular 服务都是应用程序单例.这意味着每个注入器只有一个给定服务的实例.
Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.
服务和工厂的基本区别如下:
Basically the difference between the service and factory is as follows:
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 + "!";
}
}
});
查看有关 $provide 的演示文稿:http://slides.wesalvaro.com/20121113/#/
Check out this presentation about $provide: http://slides.wesalvaro.com/20121113/#/
这些幻灯片用于 AngularJs 聚会之一:http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html
Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html
这篇关于对服务与工厂的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!