How to cancel an $http request in AngularJS?

前端 未结 8 875
面向向阳花
面向向阳花 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:34

    This feature was added to the 1.1.5 release via a timeout parameter:

    var canceler = $q.defer();
    $http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
    // later...
    canceler.resolve();  // Aborts the $http request if it isn't finished.
    
    0 讨论(0)
  • 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();
              }
           });
        });
    
    0 讨论(0)
提交回复
热议问题