如何在 $state 更改时使用 promis 取消所有待处理的 $resource 请求

How to cancel all pending $resource requests using promis on $state change

我试图在状态更改时停止所有待处理的请求 occurs.The 下面的代码适用于 $http 但不适用于 $resource。

                 var cancel=$q.defer();
    $http.get('api/cafservicestatus',{timeout:cancel.promise,cancel:cancel}).then(onsuccess,onerror);

    function onsuccess(result) {
        console.log(result)
    }

    function onerror(error) {
        console.log(error)
    }


    function stopHttp() {
        $http.pendingRequests.forEach(function(request) {
            if (request.cancel) {
                request.cancel.resolve();
            }
        });
    }

但此代码不适用于 $resource 这是 $resource

的示例代码
             $resource(resourceUrl, {}, {
        'query': { method: 'GET', isArray: true,timeout:$q.defer().promise,cancel:$q.defer()},
        'get': {
            method: 'GET',
            transformResponse: function (data) {
                if (data) {
                    data = angular.fromJson(data);
                }
                return data;
            }
        },
        'update': { method:'PUT' }
    }); 

如何使用 $resource

停止所有请求

我发现 one.You 必须向您的请求添加一个 cancellable:true 并使用 $resource 的 $cancelRequest() 方法在您的控制器中取消请求。

例如,在你的情况下

$resource(resourceUrl, {}, {
    'query': { method: 'GET', isArray: true,cancellable:true},
    'get': {
        method: 'GET',
        transformResponse: function (data) {
            if (data) {
                data = angular.fromJson(data);
            }
            return data;
        }
    },
    'update': { method:'PUT' }
}); 

在你的控制器里

 var aborted= YourService.query();

//and later on state change

  $scope.$on('$stateChangeSuccess',function(event){
     aborted.$cancelRequest();
      }
      );