我目前有一个角度应用程序,它在用户登录时调用服务以开始服务器调用以刷新计数,如果用户通过身份验证,则只允许服务器端返回。
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);
}
问题是,即使我在 $timeout 从服务器返回 401 时调用取消后,计数器仍继续运行。控制台注销返回取消函数返回true(取消已经生效)。我尝试了几种不同的 $timeout 开头的位置都无济于事,有没有办法确保所有的 $timeout 都被取消?我不明白我在这个配置中缺少什么。
编辑
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;
}]);