我在一个Ionic / Angular应用程序中使用Angular和RxJS observables进行HTTP API调用。
this.http
.post('https://API URL', data, {
headers: headers
}).map(response => response.json()).subscribe(
(res) => {},
(err) => {}
);
要求是,如果API请求花费太多时间说10-12s给出成功或错误,即200或500等响应,那么我想触发一些其他模态popUp或ui元素并保持处理,API请求为其是,发生在后台并通知完成。
肯定有很多人会这样做,但我个人更喜欢这个,我把所有东西放在一个链中:
this.http.post(...)
.merge(Observable.timer(10 * 1000)
.do(() => /* Show a notification or whatever */)
.filter(() => false) // Never pass through this value
)
.take(1) // This is required to complete the chain immediately after the source Observable emits without waiting for the merged one to complete as well
.subscribe(...)
你使用timeout
方法来实现这一目标。
this.http
.post('https://API URL' , data , {
headers : headers
})
.timeout(10000) // 10 seconds
.map(response => response.json())
.subscribe(
(res) => {},
(err)=>{ console.log(err)} // TimeoutError: Timeout has occurred
);
当另一个发出值时,您可以使用takeUntil取消一个observable。分享,这样你就不会发出两个请求。
const source = this.http.post().pipe(share());
source.subscribe(console.log);
timer(10000).takeUntil(source).subscribe(() => console.log('It\'s taking over 10 sec'));