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

时间:2022-03-08 20:15:28

What i am trying to do is to cancel a request or stop listening for the response for a particular request . i cannot use a timeout in the request.the decision of whether to cancel or not is done only after the request is made .I have seen solutions in ajax jQuery as found in this. Is there any angular solutions for the same.i am using $http for making POST requests.

我想要做的是取消请求或停止侦听特定请求的响应。我不能在请求中使用超时。是否取消的决定只在请求发出后才能完成。我已经看到了ajax jQuery中的解决方案。是否有相同的角度解决方案。我使用$ http来发出POST请求。

2 个解决方案

#1


This is described in the documentation:

这在文档中描述:

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

timeout - {number | Promise} - 超时(以毫秒为单位),或承诺在解决时应中止请求。

So, when sending the request, pass a promise to the configuration timeout, and resolve it when you decide to abort:

因此,在发送请求时,将promise传递给配置超时,并在您决定中止时解决它:

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

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

#2


Just to add a coffeescript version I've used recently:

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

canceller = $q.defer()

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

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

#1


This is described in the documentation:

这在文档中描述:

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

timeout - {number | Promise} - 超时(以毫秒为单位),或承诺在解决时应中止请求。

So, when sending the request, pass a promise to the configuration timeout, and resolve it when you decide to abort:

因此,在发送请求时,将promise传递给配置超时,并在您决定中止时解决它:

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

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

#2


Just to add a coffeescript version I've used recently:

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

canceller = $q.defer()

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

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