Angular 6,每隔几秒钟调用一次API,或者每隔几秒钟从订阅接收一次新数据



给定一个简单的HTTP调用:

object: Object;
this.http.get<any>( this._globals.apiServer + 'api/data', {responseType: 'json'})
.subscribe((resp: any) => {
this.object = resp;
})

如何修改它,以便每 3 秒使用全新数据刷新一次对象?

您可以使用SetTimeoutSetInterval;

  • 如果您希望下一个请求在 最后,使用SetTimeout
  • 如果您希望请求每 3 秒准确获取一次,而不管 最后一个请求花费了多长时间(或者即使它仍在进行(,请使用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);
}
}

使用可观察的间隔并关闭它。

interval(3000).pipe(
switchMapTo(this.http.get<any>( this._globals.apiServer + 'api/data', {responseType: 'json'}))
)
.subscribe((resp: any) => {
this.object = resp;
})

笔记:

  1. 如果组件/服务被销毁,则需要取消订阅此可观察量。

  2. 这将在 3 秒后开始,要立即开始,请改为timer(0, 3000)

最新更新