角$ HTTP超时返回undefined [英] Angular $http timeout returning undefined
问题描述
我只是测试用角的$ HTTP模块的超时功能,但它一直返回undefined作为响应
I'm just testing the timeout functionality with Angular's $http module, however it keeps returning undefined as the response
这是罚款,如果设置就是这样的,但如果我钉在 .error(功能)
而不是。然后(功能)
,到 $ HTTP
呼叫时,它抛出试图从一个未定义的对象获取数据字段中的错误
It's fine if set up just like this, but if I tack on .error(function)
instead of .then(function)
, to the $http
call, it throws an error trying to grab the data field from an undefined object
var timeout = $q.defer();
var config = {
url: 'http://192.168.1.65:3000',
timeout: timeout.promise,
method: 'POST'
};
$http(config).then(function(res) {
// This is always undefined when timeout occurs
console.log(res);
});
$timeout(function() {
console.log('resolving the promise to abort the http call. This works fine');
timeout.resolve();
}, 1000);
任何想法我做错了吗?
Any ideas what I'm doing wrong?
推荐答案
在 $ HTTP
倍出,它返回一个拒绝承诺,你可以用<$ C处理$ C> .catch :
When $http
times-out, it returns a rejected promise that you can handle with .catch
:
$http(config)
.then(function(response){
})
.catch(function(error){
// will fire when timed out
})
题外话:它实际上是简单的只使用由 $超时
,产生无需 $ q.defer $的承诺C $ C>:
Off-topic: it's actually simpler to just use the promise generated by $timeout
, without the need for $q.defer
:
var timeout = $timeout(angular.noop, 1000);
$http.get(url, {timeout: timeout})
.then(...)
.catch(...)
编辑:
在情况下,有一个拦截器,则超时将导致 responseError
,如果定义,拦截器基本上是处理的错误,使之不再成为拒绝承诺并将结果发送到。然后
- 如果你不返回从 responseError
函数的任何信息,数据传递到。然后
处理程序未定义
。如果你想保留拒绝,你可以这样做:
In case there is an interceptor, then the timeout would result in responseError
, and if defined, that interceptor essentially "handles" the error so it no longer becomes a rejected promise and the result is routed to .then
- and if you do not return anything from the responseError
function, the data passed to the .then
handler is undefined
. If you want to keep the rejection, you can do:
// inside http inteceptor
responseError: function(rejection){
if (rejection.status === 0){ // if timeout
return $q.reject({reason: "timeout"});
}
// ...
}
这篇关于角$ HTTP超时返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!