Angular $ http配置超时

时间:2016-06-28 00:27:51

标签: javascript angularjs httprequest angular-promise angular-http

如角度文档中所述,

  

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

现在我将超时设置为承诺,因此我可以通过promise.resolve()手动取消请求。

现在,我还希望能够配置超时值,而不是让请求超时为120秒。

如何在不影响现有取消请求功能的情况下进行配置?

1 个答案:

答案 0 :(得分:3)

你可以做这样的事情

$scope.qPromiseCall = function()
{
       var timeoutPromise = $timeout(function()
       {       
               //aborts the request when timed out
               canceler.resolve(); 
               console.log("Timed out");
        }, 250); 

//we set a timeout for 250ms and store the promise in order to be cancelled later if the data does not arrive within 250ms

     var canceler = $q.defer();
     $http.get("data.js", {timeout: canceler.promise} )
     .success(function(data)
     {
           console.log(data);
           $timeout.cancel(timeoutPromise);
           //cancel the timer when we get a response within 250ms
    });

  }

有关详细信息,请参阅

Setting a timeout handler on a promise in angularjs

@Khanh TO的第一个回答