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

时间:2014-02-20 17:56:55

标签: angularjs promise

在Angular $http docs中,它提到您可以将'timeout'配置设置为数字或承诺。

  

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

但我不知道如何使用承诺来完成这项工作。我如何设定数字和承诺? 基本上我希望能够知道由于“超时”或其他原因而导致的http调用(promise)是否存在错误。我需要能够区分它们。 谢谢你的帮助!!!

3 个答案:

答案 0 :(得分:34)

此代码来自$httpBackend source code

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)表示当promise被解决(未被拒绝)时,将调用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);
});

答案 1 :(得分:2)

我有一个类似的问题,你可以查看这个链接:Angular 1.5 timeout using a HttpInterceptor关于如何在httpInterceptor中实现超时。 jsFiddle包含在anwser中。所有积分都会转到https://stackoverflow.com/users/3959997/mita以获得答案。

答案 2 :(得分:0)

我正在使用嵌入式系统,因为它是一台物理设备,我不时会出现问题,所以使用$ timeout修复此行为时,它会持续数天/数月/年

快速示例(http promises的超时包装)

模块

var myApp = angular.module('myApp',['ngRoute']);

服务

var yourServiceModule = myApp.service('YourService', function ($http) {
    this.your_method = function (a) { return a*a};
});

控制器

//just wrap your service,http call using $timeout
$timeout(function() {
    //vanilla service call
    YourService.your_method().then(
              function (response) {
                 //console.log("sync_with_cloud: "+ response);
                 $scope.check_cloud_port_statuses_progress=100;
                 //...
             },
              function(data) {
                  // Handle error here

                $rootScope.global_config_1 += "\nError(333): cant connect to cloud at "+Date.now();+"\n\n";
                $scope.check_cloud_port_statuses_progress = -1;
              }
    );

}, 8);