How to cancel an $http request in AngularJS?

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

    For some reason config.timeout doesn't work for me. I used this approach:

    let cancelRequest = $q.defer();
    let cancelPromise = cancelRequest.promise;
    
    let httpPromise = $http.get(...);
    
    $q.race({ cancelPromise, httpPromise })
        .then(function (result) {
    ...
    });

    And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.

    Hope this helps.

提交回复
热议问题