我目前有一个角度应用程序,在用户登录时调用服务来开始服务器调用以刷新计数,只有在用户通过身份验证时才允许服务器端返回。
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
return resource.query({
username: username,
q: 'approvalsCount'
}).$then(function (response) {
resource.approvalsCount = response.data.count;
approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
return resource.approvalsCount;
});
};
当用户注销时,我试图取消该计数器,否则服务器将通过调用基于资源的函数返回401未经授权的错误:
resource.cancelTimers = function () {
$timeout.cancel(approvalsCountTimer);
}
问题是,即使在我从服务器返回401的$ timeout调用取消后,计数器仍继续运行。控制台注销返回取消函数返回true(取消已经工作)。我已经尝试了$ timeout的开头几个不同的位置无济于事,有没有办法确保所有$ timeouts都被取消?我不明白我在这个配置中缺少什么。
修改
angular.module('resources.approvals.approvals', ['ngResource'])
.factory('Approvals', ['$timeout', '$resource', function ($timeout, $resource) {
var resource = $resource('/approvals/:username/:requestID', {}, {
'update': {
method: 'PUT'
}
});
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
return resource.query({
username: username,
q: 'approvalsCount'
}).$then(function (response) {
resource.approvalsCount = response.data.count;
approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
return resource.approvalsCount;
});
};
resource.cancelTimers = function () {
$timeout.cancel(approvalsCountTimer);
};
return resource;
}]);
答案 0 :(得分:1)
我认为你的代码看起来不错。它必须是别的东西。
我简化了一下,你可以在demo上看到它。它每半秒模拟一次http调用,cancelTimes
将在4秒内调用。
app = angular.module('app', []);
app.factory('Approvals', ['$timeout', function ($timeout) {
var resource = {};
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
console.log(approvalsCountTimer);
approvalsCountTimer = $timeout(resource.getApprovalsCount, 500);
};
resource.cancelTimers = function () {
console.log("stopped");
$timeout.cancel(approvalsCountTimer);
};
return resource;
}]);
function Ctrl($scope, $timeout, Approvals) {
Approvals.getApprovalsCount();
$timeout(Approvals.cancelTimers, 4000)
}