【发布时间】:2020-09-30 17:47:36
【问题描述】:
这只是看起来像这样的常规请求:
this.people = http.get('http://localhost:3000/users')
.map(response => response.json());
有没有办法延迟/超时?
【问题讨论】:
这只是看起来像这样的常规请求:
this.people = http.get('http://localhost:3000/users')
.map(response => response.json());
有没有办法延迟/超时?
【问题讨论】:
您可以利用 observables 的 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);
【讨论】:
.retryWhen(errors => errors.delayWhen(() => Observable.timer(1000))) 使用 rxjs 5.0.2。 learnrxjs.io/operators/error_handling/retrywhen.html
Http 类来全局设置超时。更多详情请看这篇文章:restlet.com/company/blog/2016/04/18/…
http.get() 的返回值是一个 observable,而不是响应。
你可以像这样使用它:
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();
}
另见https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md
【讨论】:
timeout 没有任何效果(意味着没有延迟),但是当我使用 delay(1000) 时,它可以处理延迟 1 秒的数据。我已经导入了`'rxjs/add/operator/timeout'`,但即使我输入timeout(5000),我也会立即得到数据。超时是否有不同于仅仅延迟数据的作用?
getPeople.subscribe(data => this.people = data),注意粗箭头:=>
如果您使用的是 RxJS 版本 6 及更高版本,则当前语法如下:
从 'rxjs/operators' 导入 { timeout };
getPeople(){
return this.http.get(API_URL)
.pipe(
timeout(5000) //5 seconds
);
【讨论】:
与新版本一样,您必须pipe 才能使用timeout。要获得回复,您可以在里面使用map。完整的代码如下。
import { map, timeout, catchError } from 'rxjs/operators';
const sub: any = this.httpClient.post(this.baseUrl, body)
.pipe(timeout(Config.SesamTimeout),
catchError((err: any) => {
this.handleTimeout(err);
return of(null);
}),
map((v: SesamResponse) => {
if (v) {
const a: SearchResultGroup[] = this.convertSesamResponseToApiFileItem(v);
return a;
}
}));
这里的Config.SesamTimeout 是以毫秒为单位的时间。
【讨论】: