告诉AngularJs通过依赖注入返回一个新的实例 [英] Tell AngularJs to return a new instance via Dependency Injection
问题描述
用例很简单:我有两个控制器共享相同的依赖为MyService
。这项服务是持有一些国家,让国家税务总局 MYVARIABLE
。如果我将它从 ControllerOne
,那么它将被也被 ControllerTwo
发现。
The use case is simple: I have two controllers sharing the same dependency MyService
. This service is holding some state, lets sat myVariable
. If I set it from ControllerOne
, then it will be also spotted by ControllerTwo
.
我要的是每个控制器有它的为MyService
的自己的实例,使 MYVARIABLE
是可以改变的通过不影响其他每个控制器。
What I want is for each controller to have it's own instance of MyService
, so that myVariable
can be changed by each Controller without affecting the other.
要把它放在另一个的话 - 我要的新实例由依赖注入返回,而不是单
To put it in another words - I want new instance to be returned by Dependency Injection, rather than singleton.
推荐答案
还不如直接有你可能希望。服务实例被创建他们由喷射器检索和由喷射器保持在第一时间...换言之,他们总是单身。 魔术在这里发生,尤其是看提供商
功能,这使提供者实例在providerCache对象。
Not as directly has you might hope. Service instances are created the first time they're retrieved by the injector and maintained by the injector... in other words, they're always singletons. The magic happens in here, particularly look at the provider
function, which puts the provider instance in the providerCache object.
但是,不要失去希望,你可以很容易地添加构造函数无论是你想在一个服务共享,如果你选择了这样:
But don't lose hope, you could just as easily add constructors for whatever it is you want to share in a Service, if you so chose:
app.factory('myService', [function() {
var i = 1;
function Foo() {
this.bar = "I'm Foo " + i++;
};
return {
Foo: Foo
};
}]);
app.controller('Ctrl1', function($scope, myService) {
$scope.foo = new myService.Foo();
console.log($scope.foo.bar) //I'm Foo 1
});
app.controller('Ctrl2', function($scope, myService) {
$scope.foo = new myService.Foo();
console.log($scope.foo.bar) //I'm Foo 2
});
编辑:作为OP指出,这里也是 $ injector.instantiate ,你可以用打电话给你的控制器的外部的JavaScript构造函数。我不知道什么样的影响是可测性的在这里,但它确实给你另一种方式来注入code,将构造一个新的对象适合你。
as the OP pointed out, there is also the $injector.instantiate, which you can use to call JavaScript constructors outside of your controller. I'm not sure what the implications are of the testability here, but it does give you another way to inject code that will construct a new object for you.
这篇关于告诉AngularJs通过依赖注入返回一个新的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!