【问题标题】:AngularJS: How to Abort a http request that i have not yet received the responseAngularJS:如何中止我尚未收到响应的 http 请求
【发布时间】:2015-07-13 11:13:58
【问题描述】:

我要做的是取消请求或停止侦听特定请求的响应。我不能在请求中使用timeout。只有在发出请求后才决定是否取消。我在ajax jQuery as found in this 中看到了解决方案。是否有相同的角度解决方案。我正在使用$http 发出 POST 请求。

【问题讨论】:

标签: angularjs xmlhttprequest


【解决方案1】:

这在the documentation中有描述:

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

因此,在发送请求时,向配置超时传递一个承诺,并在您决定中止时解决它:

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

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

【讨论】:

  • 我可以知道哪个角度版本支持超时的承诺对象。我使用的是 v1.2.26
  • 确定:进入文档页面,确保选择左上角的1​​.2.26版本,看看那个版本是否支持。
【解决方案2】:

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

canceller = $q.defer()

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-20
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多