How to cancel an $http request in AngularJS?

前端 未结 8 960
面向向阳花
面向向阳花 2020-11-22 09:49

Given a Ajax request in AngularJS

$http.get(\"/backend/\").success(callback);

what is the most effective way to cancel that request if anot

8条回答
  •  悲&欢浪女
    2020-11-22 10:36

    If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:

    // in service

                    var deferred = $q.defer();
                    var scope = this;
                    $http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
                        //do something
                        deferred.resolve(dataUsage);
                    }).error(function(){
                        deferred.reject();
                    });
                    return deferred.promise;
    

    // in UIrouter config

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        //To cancel pending request when change state
           angular.forEach($http.pendingRequests, function(request) {
              if (request.cancel && request.timeout) {
                 request.cancel.resolve();
              }
           });
        });
    

提交回复
热议问题