我已經定義了服務這樣的條件注:在AngularJS服務
angular.module('myApp').service('myService', [
'$rootScope',
...
...
我只希望新用戶被實例化我的服務(即當user.createdAt>今天)。
因此,如果用戶是舊的,那麼是否有條件地注入我的服務或至少銷燬我的服務而沒有任何副作用。
我已經定義了服務這樣的條件注:在AngularJS服務
angular.module('myApp').service('myService', [
'$rootScope',
...
...
我只希望新用戶被實例化我的服務(即當user.createdAt>今天)。
因此,如果用戶是舊的,那麼是否有條件地注入我的服務或至少銷燬我的服務而沒有任何副作用。
可以使用$injector
服務來獲取動態注入,ibles如果您需要:
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
而$injector
文檔:https://docs.angularjs.org/api/auto/service/$injector
作爲一般指導,雖然我建議不設計您的服務,只需注射它們有副作用。
的使用factory
代替service
,讓你可以在你的服務有一定的檢查邏輯
angular.module('myApp').factory('myService', function() {
if (newUser) {
return { // your service implementation here
}
}
return undefined;
};
因此,如果用戶是舊的,那麼是否有條件地注入我的服務或至少銷燬我的服務,沒有任何副作用。
最佳捕捉到了這個邏輯裏面的服務:
class Service{
static $inject = ['$rootScope'];
constructor($rootScope){
if (user.createdAt > today){ /*something*/ }
else {/*other thing*/}
}
}
注:服務單身所以有條件的注射不會看到像一個理想的解決方案。 也要了解一下$注:https://www.youtube.com/watch?v=Yis8m3BdnEM