我使用Angular2' http.post
,有时标题不会发送到CORS服务器。所以我想尝试直到请求成功。但是这段代码无休止地挂起了?
var headers = new Headers();
headers.append('Content-Type', 'text/plain');
this.again = true;
while (this.again==true) {
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.subscribe(
(res2) => {
try {
this.ip = res2.json();
this.ipstr = this.ip.replace(/\./g, '-');
this.again = false;
}
catch (err) {
console.error(err);
}
}
);
}
答案 0 :(得分:1)
如果您想从请求中捕获错误,您可以:
使用subscribe
方法的第二个回调:
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.subscribe(
(res2) => {
(...)
},
(error) => {
(...)
}
);
}
使用catch
运算符:
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.catch((error) => {
(...)
})
.subscribe(
(res2) => {
(...)
}
);
}
关于重试请求,您可以通过这种方式利用retry
运算符(使用timeout
):
this.http.get('https://localhost:44300/account/getip',
{ search: params })
.retryWhen(error => error.delay(500))
.timeout(2000, return new Error('delay exceeded'))
.map(res => res.json().postalCodes);
您可以看到使用delay
在执行新请求之前等待一段时间......
这篇文章也会引起你的兴趣:
答案 1 :(得分:1)
您可以使用retry
运算符:
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.retry(3)
.subscribe((res2) => {
this.ip = res2.json();
this.ipstr = this.ip.replace(/\./g, '-');
})