在 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.
推荐答案
如果需要,您可以使用 $injector
服务动态获取可注入对象:
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
以及 $injector
文档: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屋!