如何取消 AngularJS 中的待处理请求?

How to cancel pending requests in AngularJS?

我有一个输入框。当这个字段上有一个 keyup 时,我发送一个带有 AJAX 和 angular 的 $http 服务的请求。我的问题是当另一个 keyup 事件被触发时,我需要取消所有待处理的请求。我看了很多答案,但我没有找到解决方案。

我尝试了两件事:

我调用的服务

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

效果不佳。

还有这个:

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

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

这会在发送前取消所有请求。

你能帮帮我吗?

由于您注册的是工厂而不是服务,因此您不必使用 'this',您的函数不会 treated/instanciated 作为带有 new 关键字的构造函数。

你需要一个服务来维护每个发起请求的取消器,并在发送另一个请求时取消之前的请求

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