2

我目前有一个角度应用程序,它在用户登录时调用服务以开始服务器调用以刷新计数,如果用户通过身份验证,则只允许服务器端返回。

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;
}]);
4

1 回答 1

1

我认为您的代码看起来不错。它必须是别的东西。

我简化了一点,您可以在演示中看到它。它每半秒模拟一次 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)
}
于 2013-08-08T18:52:07.860 回答