How to cancel pending requests in AngularJS?

I have an input field. When there is keyup in this field, I send a request with AJAX and $ http angular service. My problem is that when another keyup event is fired, I need to cancel all pending requests. I saw a lot of answers, but I did not find a solution.

I tried two things:

The service that I call

App.factory('findArticlesService', function($http, $q) {
   var self = this;
   self.canceller = null;

   return {
       getArticles: function(route, formData) {
           if (self.canceller) {
               self.canceler.resolve("Other request is pending");
           }

           var deferred = $q.defer();
           self.canceller = $q.defer();

           $http.post(route, angular.toJson(formData), {timeout: self.canceller.promise}).success(function(data) {
                deferred.resolve({data: data}); 
           });

           return deferred.promise;
       }
   };
});

App.controller('mainCtrl', ['$scope', '$http', '$q', 'findArticlesService', function($scope, $http, $q, findArticlesService) {
    var res = findArticlesService.getArticles(route, $scope.formData);
    console.log(res);
}]);

This does not work.

And this:

var canceller = $q.defer();
canceller.resolve();

$http.post(route, angular.toJson($scope.formData), {timeout: canceller.promise}).then(function(data) {...});

Cancel all requests before sending them.

Can you help me?

+4
source share
1 answer

Since you are registering a factory, not a service, you do not need to use 'this', your function will not be processed / created as a constructor with a new keyword.

, ,

App.factory('findArticlesService', function($http, $q) {
  var canceller;

   return {
       getArticles: function(route, formData) {
           if (canceller) {
               canceller.resolve("Other request is pending");
           }
           canceller = $q.defer();

           return $http.post(route, angular.toJson(formData), {timeout: canceller.promise});

       }
   };
});

-, ,

App.factory('findArticlesService', function($http) {
  var canceler,
      getArticles = function (route, formData) {
        if (canceler) {
          canceler.resolve('aborted');
        }
        canceler = $http.post(route, angular.toJson(formData), {timeout: canceler.promise});
        return canceler;
      };

  return {
   getArticles: getArticles
 };
});
+2

All Articles