Angularjs 服务如何判断注入它的控制器是否已损坏?
我有一个服务,轮询服务器并缓存结果,我希望它停止这样做,并在不再需要时清除缓存。以下是我尝试过的:Angularjs 服务如何判断注入它的控制器是否已损坏?,angularjs,dependency-injection,Angularjs,Dependency Injection,我有一个服务,轮询服务器并缓存结果,我希望它停止这样做,并在不再需要时清除缓存。以下是我尝试过的: angular.module('app', []). service('MyService', function(){ var cache = []; var ctrls = 0; return { init: function(scope){ // Keep track of how many controllers have
angular.module('app', []).
service('MyService', function(){
var cache = [];
var ctrls = 0;
return {
init: function(scope){
// Keep track of how many controllers have injected this service
ctrls++;
// Also keep track of how many of those controllers get destroyed
scope.$on('$destroy', function(){
ctrls--;
// Clear the cache once it's not needed!
if(ctrls === 0){cache.length = 0;}
});
}
}
}).
controller('MyController', function($scope, MyService){
MyService.init($scope);
});
虽然这是可行的,但它很容易出错,并且依赖于控制器上的代码才能正常工作
有没有一种标准的、有角度的方法可以知道什么时候注入这个东西的东西不再存在于服务本身中,而不依赖于服务本身之外的代码?一种很好的方法是装饰$injector,但这是不可能的。 但是,您可以重写$injector的get函数,然后调用原始get,如下所示:
angular.module('yourApp').config(['$injector', function ($injector) {
// The function we'll be called after the original get
counterFunc = function () {
// do your counting here
console.log("injector called ", arguments[0]);
};
// Get a copy of the injector's get function
var origGetFunc = $injector.get;
//Override injector's get with our own
$injector.get = function() {
// Call the original get function
var returnValue = origGetFunc.apply(this, arguments);
// Call our function
counterFunc.apply(this,arguments);
return returnValue;
}
}]);