问题描述
此代码来自$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$http
docs中,它提到您可以将“超时”配置设置为数字或承诺。
超时 – {number | Promise} –超时(以毫秒为单位),或承诺应在解决后中止请求。
但是我不确定如何使用诺言使这项工作成为现实。我如何设定数字和承诺?基本上,我希望能够知道http调用(承诺)是否由于“超时”或其他原因而出错。我需要能够分辨出差异。谢谢你的帮助
!!!