给出一个简单的HTTP调用:
object: Object;
this.http.get<any>( this._globals.apiServer + 'api/data', {responseType: 'json'})
.subscribe((resp: any) => {
this.object = resp;
})
我该如何修改它,以便每3秒钟用全新的数据刷新对象?
interval(3000).pipe(
switchMapTo(this.http.get<any>( this._globals.apiServer + 'api/data', {responseType: 'json'}))
)
.subscribe((resp: any) => {
this.object = resp;
})
notes:
如果组件/服务被销毁,此可观察项需要取消订阅。
此操作将在3秒钟后开始,立即开始执行
timer(0, 3000)
代替
如果您希望下一个请求在最后,使用SetTimeout
SetInterval
object: Object;
requestTimeout;
refreshObject() {
this.http.get<any>(this._globals.apiServer + 'api/data', {responseType: 'json'})
.subscribe((resp: any) => {
this.object = resp;
// Call again in 3 seconds
this.requestTimeout = setTimeout(() => this.refreshObject(), 3000);
}, (error) => {
// Something went wrong
console.error(error);
// Try again in 3 seconds
this.requestTimeout = setTimeout(() => this.refreshObject(), 3000);
});
}
// Stop the pending request
ngOnDestroy() {
if (this.requestTimeout) {
clearTimeout(this.requestTimeout);
}
}