以下是常规请求:
this.people = http.get('http://localhost:3000/users')
.map(response => response.json());
Run Code Online (Sandbox Code Playgroud)
有什么方法可以达到/超时吗?
Thi*_*ier 37
您可以利用timeout可观察对象的运算符,如下所述:
return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
{ search: params })
.retryWhen(error => error.delay(500))
.timeout(2000, new Error('delay exceeded')) // <------
.map(res => res.json().postalCodes);
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此文章("重试支持"部分):
返回值http.get()是可观察的,而不是响应.您可以像以下一样使用它:
getPeople() {
return http.get('http://localhost:3000/users')
.timeout(2000)
.map(response => response.json());
}
}
foo() {
this.subscription = getPeople.subscribe(data => this.people = data)
}
// to cancel manually
cancel() {
this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
另请参见https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md
小智 5
如果您使用的是 RxJS 6 及以上版本,当前的语法是这样的:
从'rxjs/operators'导入{超时};
getPeople(){
return this.http.get(API_URL)
.pipe(
timeout(5000) //5 seconds
);
Run Code Online (Sandbox Code Playgroud)