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

请先检查代码

app.js

var app = angular.module('Nimbus', ['ngRoute']);

route.js

app.config(function($routeProvider) {

$routeProvider

.when('/login', {

controller: 'LoginController',

templateUrl: 'templates/pages/login.html',

title: 'Login'

})

.when('/home', {

controller: 'HomeController',

templateUrl: 'templates/pages/home.html',

title: 'Dashboard'

})

.when('/stats', {

controller: 'StatsController',

templateUrl: 'templates/pages/stats.html',

title: 'Stats'

})

}).run( function($q, $rootScope, $location, $route, Auth) {

$rootScope.$on( "$routeChangeStart", function(event, next, current) {

console.log("Started");

/* this line not working */

var canceler = $q.defer();

canceler.resolve();

});

$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){

$rootScope.title = ($route.current.title) ? $route.current.title : 'Welcome';

});

})

home-controller.js

app.controller('HomeController',

function HomeController($scope, API) {

API.all(function(response){

console.log(response);

})

}

)

stats-controller.js

app.controller('StatsController',

function StatsController($scope, API) {

API.all(function(response){

console.log(response);

})

}

)

api.js

app.factory('API', ['$q','$http', function($q, $http) {    

return {

all: function(callback) {

var canceler = $q.defer();

var apiurl = 'some_url'

$http.get(apiurl,{timeout: canceler.promise}).success(callback);

}

}

}]);

当我从家搬到stats时,API再次发送http请求,我有很多这样的http调用,我只粘贴了几行代码。

我需要做的是 取消 在routechangestart或成功时中止所有未决的http请求的操作

或任何其他方式来实现相同?

回答:

为此,我整理了一些概念代码。可能需要进行调整以满足您的需求。有一种pendingRequests服务具有用于添加,获取和取消请求的API,该服务httpService可以包装$http并确保跟踪所有请求。

通过利用$httpconfig对象(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();

}

}]);

以上是 AngularJS在路由更改时中止所有未决的$ http请求 的全部内容, 来源链接: utcz.com/qa/397452.html

回到顶部