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

问题描述

此代码来自$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( ),例如:

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$httpdocs中,它提到您可以将“超时”配置设置为数字或承诺。

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...