0

How can I abort my pending ajax requests in AngularJS? I am using a Service for making an ajax call and want to abort all pending requests if a new one is made on the same route.

Here is my service:

myService.service('angService', function($http){

  this.getfromRemote=function(url){
    return $http.get(location+'/dev/apiv-1-0-2/'+url);
  }
});

Here I am calling the service. Before running next, I want to abort the pending ajax requests.

angService.getfromRemote('paymentStatement/'+$scope.username)
                            .success(function(response){

})
pwhty
  • 7
  • 1
  • 5
ak1111
  • 107
  • 11

1 Answers1

0

To abort a pending $http request, you can pass a promise to the timeout property of the $http request, and call resolve to abort the request.

myService.service('angService',function($http, $q){
    var pending = false;
    var deferred = $q.defer();

    this.getfromRemote=function(url){
        if (pending) {
           deferred.resolve();
           deferred = $q.defer();
        }
        pending = true;
        return $http({ 
           method: 'GET', 
           url: location+'/dev/apiv-1-0-2/'+url,
           timeout = deferred.promise;
        }).then(function(result) {
           pending = false;
           deferred = $q.defer();
           return result;
        }, function(result) {
           pending = false;
           deferred = $q.defer();
           return result;
        });


    }

});
Michael Kang
  • 52,003
  • 16
  • 103
  • 135