AngularJS abort all pending $http requests on route change

前端 未结 4 1983
日久生厌
日久生厌 2020-11-28 03:09

Please go through the code first

app.js

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

route.js

app.config(fu         


        
4条回答
  •  广开言路
    2020-11-28 04:15

    You can use $http.pendingRequests to do that.

    First, when you make request, do this:

    var cancel = $q.defer();
    var request = {
        method: method,
        url: requestUrl,
        data: data,
        timeout: cancel.promise, // cancel promise, standard thing in $http request
        cancel: cancel // this is where we do our magic
    };
    
    $http(request).then(.....);
    

    Now, we cancel all our pending requests in $routeChangeStart

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
    
        $http.pendingRequests.forEach(function(request) {
            if (request.cancel) {
                request.cancel.resolve();
            }
        });
    });
    

    This way you can also 'protect' certain request from being cancelled by simply not providing 'cancel' field in request.

提交回复
热议问题