无法使用 $resource 取消请求

Unable to cancel request with $resource

在尝试了一些类似这样的解决方案后:我无法取消使用 $resource 发出的请求。 我最后一次尝试是这样的:

控制器:

angular.module('theApp')
  .controller('homeController', function ($q, foodTypeFactory) {
    var vm = this;

    vm.testButton = function () {
      vm.aborter = $q.defer();
      foodTypeFactory(vm.aborter).getTest({}, function (data) {
        console.log(data);
      });
    };
    vm.cancelButton = function () {
      vm.aborter.resolve();
    }
  });

食品类型工厂:

angular.module('theApp')
  .factory('foodTypeFactory', function ($resource, BACKEND_API) {
    return function (aborter) {
      return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '@id'}, {
        getTest: {
          timeout: aborter.promise
        }
      });
    }
  });

一旦发出请求,即使我尝试取消它,它也会完成。 我正在使用 Angular 1.6.2 和 angular-资源 1.6.2.

我做错了什么?

我可以向您建议的是使用 HTTP 拦截器.. 您可以停止请求...像这样的东西:

1) 创建一个文件,如 (auth.interceptor.js:

"use strict";

angular
.module("demo")
.factory('authInterceptorService', ['$q', '$location', 'localStorageService',
function ($q, $location, localStorageService) {
    // Public Method
    return {
        request: function (config) {
            config.headers = config.headers || {};

           if(!MYCONDITION){ //<-- you can here your logic to test if conitnue request flow or not
            return; //<-- TERMINATE IT ..
           }else{
            return config; //<-- CONTINUE WITH NORMAL REQUEST
           }


        }
    };
}]);

2) 在您的 app.config.js 文件中:

 $httpProvider.interceptors.push("authInterceptorService");

然后在您的所有请求中(通过 $http 或通过 $resource)应用此逻辑...如果需要,您还可以在此处注入 Bearer Token

希望对你有帮助

终于找到解决办法了! 从 angular 1.5 开始,可以使用 $cancelRequest() 取消 $resource。 就我而言:

控制器:

angular.module('theApp')
  .controller('homeController', function (foodTypeFactory) {
    var vm = this;

    vm.testButton = function () {
      vm.onGoingRequest = foodTypeFactory.getTest({}, function (data) {
        console.log(data);
      });
    };
    vm.cancelButton = function () {
       vm.onGoingRequest.$cancelRequest();
    }
  });

食品类型工厂:

angular.module('theApp')
  .factory('foodTypeFactory', function ($resource, BACKEND_API) {
      return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '@id'}, {
        getTest: {
          cancellable: true
        }
      });
  });