小编典典

Angular $ http:在'timeout'配置上设置一个承诺

angularjs

在Angular$httpdocs中,它提到您可以将“超时”配置设置为数字或承诺。

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

但是我不确定如何使用诺言使这项工作成为现实。我如何设定数字和承诺?基本上,我希望能够知道http调用(承诺)是否由于“超时”或其他原因而出错。我需要能够分辨出差异。谢谢你的帮助
!!!


阅读 630

收藏
2020-07-04

共1个答案

小编典典

此代码来自$httpBackend源代码

if (timeout > 0) {
  var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (timeout && timeout.then) {
  timeout.then(timeoutRequest);
}

function timeoutRequest() {
  status = ABORTED;
  jsonpDone && jsonpDone();
  xhr && xhr.abort();
}

timeout.then(timeoutRequest) 表示在解决承诺(不拒绝)后,将调用timeoutRequest并中止xhr请求。


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

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);
});
2020-07-04