在AngularJS服务的条件注入 [英] Conditional injection of a service in AngularJS
问题描述
我已经定义的服务是这样的:
I have defined a service like this :
angular.module('myApp').service('myService', [
'$rootScope',
...
...
我只希望新的用户实例化我的服务(即,当user.createdAt>今天)。
I want my service to be instantiated only for new user (i.e. when user.createdAt > today).
那么,有没有一种方法来有条件地注入我的服务或至少毁掉我的服务,无任何副作用,如果用户是旧的。
So is there a way to conditionally inject my service or at least destroy my service without any side effect if the user is an old one.
推荐答案
您可以使用 $注射器
服务来获得,如果你需要注入-ibles动态:
You can use the $injector
service to get inject-ibles dynamically if you need to:
app.controller('DemoCtrl', function($injector) {
this.clicky = function() {
myFact = $injector.get('myFactory');
myFact();
};
});
app.factory('myFactory', function() {
return function() {
alert('foobar!');
};
});
下面是一个完整的运行演示: http://jsbin.com/bemakemaja/1/edit
Here's a full running demo: http://jsbin.com/bemakemaja/1/edit
以及 $注射器
文档:的 https://docs.angularjs.org/api/auto/service/$injector
作为一般原则,虽然我不建议你设计等服务,简单地注入他们有副作用。
As a general guideline though I'd recommend not designing your services such that simply injecting them has side effects.
这篇关于在AngularJS服务的条件注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!