处理 HTTP 请求失败
Handle HTTP request failing
我有一个http
服务器的请求:
this.http.post('http://192.168.1.45:3000/testrestapi', 'user=username', {
headers: headers
})
.retry(1)
.timeout(5000)
.map(res => res.json())
.subscribe(data => {
console.log('response is ready');
}), (err) => {
console.log('error + ', err);
}, () => {
console.log('Done http request');
};
如果请求失败,我希望重试 1 次。我还希望请求在 5 秒后超时。我需要知道重试和超时是否都失败了,以便我可以处理它。
使用上面的代码,我似乎无法处理它。例如,如果请求经历了 2 次重试,我需要知道它已经进行了,以便我可以适当地处理。我以为它会出现在"错误"部分,但控制台日志根本没有打印。
首先:你迷失在括号里...subscribe
应用程序必须在回调后关闭:
this.http.post('http://192.168.1.45:3000/testrestapi', 'user=username', {headers: headers})
.timeout(3000, new Error('timeout exceeded'))
.map(res => res.json())
.retry(1)
.subscribe(data => {
console.log('response is ready');
}, (err) => {
console.log('error + ', err);
}, () => {
console.log('Done http request');
});
为了防止此类错误,TSLint 可以提供帮助。在这种情况下,我得到:
TSLint:预期的赋值或函数调用(无未使用的表达式(
第二:retry
呼叫必须在map
呼叫之后进行。
您可以尝试以下操作来处理重试:
this.http.post('http://192.168.1.45:3000/testrestapi', 'user=username', {
headers: headers
})
.retryWhen(error => error.delay(500))
.timeout(2000, () => return new Error('delay exceeded'))
.map(res => res.json())
.subscribe(data => {
console.log('response is ready');
}, (err) => {
console.log('error + ', err);
}, () => {
console.log('Done http request');
});
如果没有retryWhen
,重试将立即执行...
有关更多详细信息,请参阅此链接:
- https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html
相关文章:
- 一台特定计算机的Ajax请求数据未定义/失败
- 当我在chrome中切换设备模式时,$http.get请求失败
- Ajax错误检查-如果Ajax请求失败,如何防止内容发生更改
- Javascript-为什么我的JQueryAJAX请求失败
- Android/Chrome jQuery AJAX请求在到达服务器之前失败,并出现parserror
- 由于adblock,Javascript Ajax请求在chrome中失败,我有什么选择
- AJAX 请求不会在 400 个错误查询上执行失败
- Python POST 请求失败
- Ajax GET 请求的 URL 失败,但 hurl.it 相同 URL 的 GET 请求有效.什么给
- 对php的Angular post请求失败
- xml在使用SSL https请求时失败
- JQuery发布请求失败,发布后没有警报
- AJAX获取请求有时会在iOS Safari上失败
- Jquery Ajax请求失败
- AJAX请求json失败
- 如何根据ajax get请求的成功/失败在适当的范围内更改javascript变量
- node.js请求js与curl相比失败
- 如何判断哪个ajax请求失败
- gwt使用本机javascript向远程服务器发送POST请求失败
- 在Jasmine单元测试中,如何强制失败回调来触发失败请求