angular 终止ajax请求,如何取消AngularJS中的$http请求?

用超时值属性取消角$HTTPAjax在角1.3.15中不起作用。对于那些不能等待修复这个问题的人,我将共享一个包装在角中的jQueryAjax解决方案。

解决方案涉及两个服务:HttpService(jQueryAjax函数的包装器);

PendingRequestsService(跟踪挂起/打开的Ajax请求)

下面是PendingRequestsService服务:(function (angular) {

'use strict';

var app = angular.module('app');

app.service('PendingRequestsService', ["$log", function ($log) {

var $this = this;

var pending = [];

$this.add = function (request) {

pending.push(request);

};

$this.remove = function (request) {

pending = _.filter(pending, function (p) {

return p.url !== request;

});

};

$this.cancelAll = function () {

angular.forEach(pending, function (p) {

p.xhr.abort();

p.deferred.reject();

});

pending.length = 0;

};

}]);})(window.angular);

HttpService服务:(function (angular) {

'use strict';

var app = angular.module('app');

app.service('HttpService', ['$http', '$q', "$log", 'PendingRequestsService', function ($http, $q, $log, pendingRequests) {

this.post = function (url, params) {

var deferred = $q.defer();

var xhr = $.ASI.callMethod({

url: url,

data: params,

error: function() {

$log.log("ajax error");

}

});

pendingRequests.add({

url: url,

xhr: xhr,

deferred: deferred                });

xhr.done(function (data, textStatus, jqXhr) {

deferred.resolve(data);

})

.fail(function (jqXhr, textStatus, errorThrown) {

deferred.reject(errorThrown);

}).always(function (dataOrjqXhr, textStatus, jqXhrErrorThrown) {

//Once a request has failed or succeeded, remove it from the pending list

pendingRequests.remove(url);

});

return deferred.promise;

}

}]);

})(window.angular);

在稍后的服务中,当您加载数据时,您将使用HttpService而不是$http:(function (angular) {

angular.module('app').service('dataService', ["HttpService", function (httpService) {

this.getResources = function (params) {

return httpService.post('/serverMethod', { param: params });

};

}]);})(window.angular);

在后面的代码中,您希望加载数据:(function (angular) {var app = angular.module('app');

app.controller('YourController', ["DataService", "PendingRequestsService", function (httpService, pendingRequestsService) {

dataService    .getResources(params)

.then(function (data) {

// do stuff

});

...

// later that day cancel requests

pendingRequestsService.cancelAll();}]);})(window.angular);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值