以角$ http确定请求超时

Bil*_*rza 17 angularjs

我正在使用angular发送http请求,如下所示.

$http({
    url: url,
    params: params,
    method:'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    timeout: 60000    //60 seconds
}).success(function(data, status, headers, config) {
    //do something 
}).error(function(data, status, header, config) {
    if(timedout){  //determine occurrence of timeout.
        //invoke timeout handler
    } else  
        //handle other error
    }
});
Run Code Online (Sandbox Code Playgroud)

如何确定超时?

我观察到在这种情况下收到状态码"0".检查status == 0 for timeout是否安全?

请注意,我不是在询问HTTP请求超时(状态码408).

Bil*_*rza 19

我已经完成了如下...

var startTime = new Date().getTime();
$http.post(...)
    .success(function(resp, status, header, config) {...})
    .error(function(resp, status, header, config) {
        var respTime = new Date().getTime() - startTime;
        if(respTime >= config.timeout){
            //time out handeling
        } else{
            //other error hanndling
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方法,但检查数据== null和状态== 0没有改善我们在超时之前得到错误然后检查javaScript respTime将> = config.timeout?if(data == null && status == 0 && respTime> = config.timeout) (2认同)

zs2*_*020 6

我刚读完了源代码.在$ httpBackend的源代码中,xhr.ontimeout没有被处理.他们应该实施xhr.ontimeout.

不幸的是,Angularjs现在不支持http超时处理.:(

  • angular确实支持http超时,问题是区分超时与其他网络相关的错误. (2认同)