简体   繁体   English

防止AngularJS $ http超时返回

[英]Prevent AngularJS $http return on timeout

I am doing custom $http service that looks something like this: 我正在做自定义$http服务,看起来像这样:

angular.factory('myHttp', function($http){
    var obj = {};

    obj.get = function(path) {
        return $http.get(path,{timeout: 5000}).error(function (result) {
                console.log("retrying");
                return obj.get(path);
        });
    }
});

The system works fine. 系统工作正常。 It does return the data when success, and retrying when connection fail. 成功时会返回数据,而连接失败后会重试。 However, I am facing problem that it will return to controller when the connection is timeout. 但是,我面临的问题是,连接超时时它将返回控制器。 How can I prevent it from returning and continue retrying? 如何防止它退回并继续重试?

You need to use $q.reject . 您需要使用$q.reject This will indicate that the error handler failed again and the result should populated to the parent error handler - NOT the success handler. 这将指示错误处理程序再次失败,并且结果应填充到父级错误处理程序-而不是成功处理程序。

  obj.get = function(path) {
    return $http.get(path, {
      timeout: 5000
    }).then(null, function(result) {
      console.log("retrying");
      if (i < retry) {
        i += 1;
        return obj.get(path);
      } else {
        return $q.reject(result); // <-- use $q.reject
      }
    });
  }

See plunker 朋克

See the reject.status to determine the timeout 请参阅reject.status确定超时

  $http.get('/path', { timeout: 5000 })
    .then(function(){

      // Your request served

    },function(reject){


      if(reject.status === 0) {

         // $http timeout

      } else {

         // response error 

      }
    });

Please see the following question for a good overview about handling timeout errors: 请参阅以下问题,以获得有关处理超时错误的良好概述:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM