AngularJS: 如何中止尚未收到响应的 http 请求

AngularJS: How to Abort a http request that i have not yet received the response

我想做的是取消请求或停止侦听特定请求的响应。我不能在 request.the 中使用 timeout 是否取消的决定仅在发出请求后才完成。我在 ajax jQuery [=13] 中看到了解决方案=]. same.i 是否有任何 angular 解决方案,我正在使用 $http 发出 POST 请求。

这在the documentation中有描述:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

所以,在发送请求的时候,给配置超时传递一个promise,在你决定中止的时候解决它:

var cancelDefer = $q.defer();
$http.get(url, {
    timeout: cancelDefer.promise
}).success(...);

// later, to cancel the request:
cancelDefer.resolve("cancelled");

只是添加一个我最近使用的 coffeescript 版本:

canceller = $q.defer()

$http.get (requestUrl, { timeout: canceller.promise })
  .then (response) ->
    $scope.remoteData = response.data;

$scope.cancel = () ->
  canceller.resolve 'Cancelled http request'