AngularJS在路由更改时中止所有未决的$ http请求

AngularJS在路由更改时中止所有未决的$ http请求,第1张

AngularJS在路由更改时中止所有未决的$ http请求

为此,我整理了一些概念代码。可能需要进行调整以满足您的需求。有一种

pendingRequests
服务具有用于添加,获取和取消请求的API,该服务
httpService
可以包装
$http
并确保跟踪所有请求。

通过利用

$http
config对象(docs),我们可以获得一种取消待处理请求的方法。

我做了一个plnkr,但是您将需要快速手指才能看到请求被取消,因为我发现的测试站点通常会在半秒钟内做出响应,但是您会在devtools网络标签中看到请求确​​实被取消了。就您而言,您显然会触发

cancelAll()
来自中的适当事件的调用
$routeProvider

控制器就在那里演示该概念。

演示

angular.module('app', [])// This service keeps track of pending requests.service('pendingRequests', function() {  var pending = [];  this.get = function() {    return 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.canceller.resolve();    });    pending.length = 0;  };})// This service wraps $http to make sure pending requests are tracked .service('httpService', ['$http', '$q', 'pendingRequests', function($http, $q, pendingRequests) {  this.get = function(url) {    var canceller = $q.defer();    pendingRequests.add({      url: url,      canceller: canceller    });    //Request gets cancelled if the timeout-promise is resolved    var requestPromise = $http.get(url, { timeout: canceller.promise });    //once a request has failed or succeeded, remove it from the pending list    requestPromise.finally(function() {      pendingRequests.remove(url);    });    return requestPromise;  }}])// The controller just helps generate requests and keep a visual track of pending ones.controller('AppCtrl', ['$scope', 'httpService', 'pendingRequests', function($scope, httpService, pendingRequests) {  $scope.requests = [];  $scope.$watch(function() {    return pendingRequests.get();  }, function(pending) {    $scope.requests = pending;  })  var counter = 1;  $scope.addRequests = function() {    for (var i = 0, l = 9; i < l; i++) {      httpService.get('https://public.opencpu.org/ocpu/library/?foo=' + counter++);      }  };  $scope.cancelAll = function() {    pendingRequests.cancelAll();  }}]);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427927.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存