Angular $ http:在'timeout'配置上设置一个承诺 [英] Angular $http : setting a promise on the 'timeout' config

查看:50
本文介绍了Angular $ http:在'timeout'配置上设置一个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular $http文档中,它提到您可以设置超时"配置为数字或承诺.

In the Angular $http docs, it mentions that you can set the 'timeout' config to either a number or a promise.

超时 – {number | Promise} –超时(以毫秒为单位),或承诺 解决后应中止请求.

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

但是我不确定如何使用诺言来完成这项工作.我如何设定数字和承诺? 基本上,我希望能够知道http调用(承诺)是否由于超时"或其他原因而出错.我需要能够分辨出区别. 谢谢您的帮助!!!

But I am not sure how to make this work using a promise. how do i set a number and a promise ? Basically I want to be able to know whether an http call (promise) errored due to a 'timeout' or something else. I need to be able to tell the difference. Thanks for any help !!!

推荐答案

此代码来自 timeout.then(timeoutRequest)表示在兑现承诺(未拒绝)后,将调用timeoutRequest并中止xhr请求.

timeout.then(timeoutRequest) means that when the promise is resolved (not rejected) timeoutRequest is invoked and xhr request is aborted.

如果请求超时,则reject.status === 0(注意:如果网络出现故障,则reject.status也将等于0 ),例如:

If the request was timeout then reject.status === 0 (Note: in case of a network failure, then reject.status will also be equals to 0), An example:

app.run(function($http, $q, $timeout){

  var deferred = $q.defer();

  $http.get('/path/to/api', { timeout: deferred.promise })
    .then(function(){
      // success handler
    },function(reject){
      // error handler            
      if(reject.status === 0) {
         // $http timeout
      } else {
         // response error status from server 
      }
    });

  $timeout(function() {
    deferred.resolve(); // this aborts the request!
  }, 1000);
});

这篇关于Angular $ http:在'timeout'配置上设置一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆