栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452401.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号