代码之家  ›  专栏  ›  技术社区  ›  Harshit Bhatt

如何在$状态更改时使用promis取消所有挂起的$资源请求

  •  2
  • Harshit Bhatt  · 技术社区  · 7 年前

    当状态发生更改时,我正在尝试停止所有挂起的请求。下面的代码适用于$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(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' }
        }); 
    

    如何使用$资源停止所有请求

    1 回复  |  直到 7 年前
        1
  •  2
  •   schezwan Software    7 年前

    我已经找到了这个。您必须为请求添加一个Cancelable: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();
          }
          );