Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS abort all pending $http requests on route change

Please go through the code first

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

When I move from home to stats , again API will send http request, I have many http calls like this, I pasted only few lines of code.

What I need is I need to cancel abort all pending http requests on routechangestart or success

Or any other way to implement the same ?

like image 789
Miqdad Ali Avatar asked Apr 23 '14 12:04

Miqdad Ali


3 Answers

I put together some conceptual code for this. It might need tweaking to fit your needs. There's a pendingRequests service that has an API for adding, getting and cancelling requests, a httpService that wraps $http and makes sure all requests are tracked.

By leveraging the $http config object (docs) we can get a way to cancel a pending request.

I've made a plnkr, but you're going to need quick fingers to see requests getting cancelled since the test-site I found typically responds within half a second, but you will see in the devtools network tab that requests do get cancelled. In your case, you would obviously trigger the cancelAll() call on the appropriate events from $routeProvider.

The controller is just there to demonstrate the concept.

DEMO

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();
  }
}]);
like image 81
ivarni Avatar answered Oct 28 '22 02:10

ivarni


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.

like image 24
Frane Poljak Avatar answered Oct 28 '22 02:10

Frane Poljak


I think this is the best solution to abort requests. It's using an interceptor and $routeChangeSuccess event. http://blog.xebia.com/cancelling-http-requests-for-fun-and-profit/

like image 9
rootatdarkstar Avatar answered Oct 28 '22 02:10

rootatdarkstar