使用promises取消AngularJS中的HTTP请求

时间:2015-05-19 14:38:13

标签: javascript angularjs promise cancellation angular-http

如果用户点击另一个标签导航到其他页面,我需要能够在AgularJS中取消HTTP请求。我正在使用$ http服务的timeout属性来取消请求,因此:

$scope.myCustomers = function () {
    $scope.searchResultsPromise = $http.get('/api/customers/getmycustomers', { timeout: canceller.promise } )
        .success(function (data) { $scope.customerSearchResults = data; })
        .catch(function () { alert("There has been an error retrieving search results") }
        );
}

我正在取消这样的请求:

$scope.enquiriesSelected = function () {
    $scope.cancelHttpRequests();
    $location.path("/enquiries");
};

$scope.cancelHttpRequests = function () {
    if (canceller) canceller.resolve();
}

然而,这似乎不起作用。如果我点击查询链接导航到另一个视图,然后立即导航回包含已取消承诺的视图,该页面似乎被卡住了#39;。我无法执行任何HTTP请求。查看Fiddler表示请求已经发出,但它没有返回。

有没有人在Angular中取消HTTP请求的经验?我使用的是版本1.3.15

更新

Pierre Gayvallet,我在控制器创建功能中创建了取消器:

angular.module('App')
    .controller('customersCtrl', function ($scope, $http, $q, $location, lookupDataService) {
            // ...
            var canceller = $q.defer();
            // ...
})) // these may be incorrect!

robertklep,我将添加一些逻辑以确保承诺尚未解决。

更多信息

robertklep,似乎并不是一种检查承诺是否已经解决的推荐方法。我会尝试在范围中添加一个标志,但我不愿意用这样的东西来混淆我的代码......

中号

0 个答案:

没有答案
相关问题