Javascript http post订阅并尝试捕获
我使用Angular2的Javascript http post订阅并尝试捕获,javascript,http,typescript,angular,Javascript,Http,Typescript,Angular,我使用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/a
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);
}
}
);
}
如果要捕获请求中的错误,可以:
- 使用
方法的第二个回调: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) => { (...) } ); }
http.post('https://localhost:44300/account/getip', "", { headers: headers }) .retry(3) .subscribe((res2) => { this.ip = res2.json(); this.ipstr = this.ip.replace(/\./g, '-'); })
retry
操作符(使用timeout
one):
您可以看到使用delay
在执行新请求之前等待一段时间
您也可能会对本文感兴趣:
重试
操作符:
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.catch((error) => {
(...)
})
.subscribe(
(res2) => {
(...)
}
);
}
http.post('https://localhost:44300/account/getip', "", { headers: headers })
.retry(3)
.subscribe((res2) => {
this.ip = res2.json();
this.ipstr = this.ip.replace(/\./g, '-');
})
TypeError:http.post(…)。重试不是所有运算符的函数,您需要导入它
import'rxjs/add/operator/retry'代码>这会使我的应用程序崩溃,请尝试他们的答案。可能导入错误?我必须转换到
我在使用函数时遇到问题。我试过:import'rxjs/add/operator/timeout';导入“rxjs/add/operator/catch”
,但随后应用程序冻结了:-(你是否尝试过:导入'rxjs/Rx';
。看看会发生什么…这也冻结了我的浏览器你能打开JavaScript控制台看看SystemJS加载了什么吗?我很笨。我的代码中仍然有而循环。现在它可以工作了。谢谢!