[英]Angular 6, call API every few seconds or receive new data from subscription every few seconds
給定一個簡單的 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;
})
筆記:
如果組件/服務被銷毀,則需要取消訂閱此 observable。
這將在 3 秒后開始,立即開始執行timer(0, 3000)
代替
您可以使用SetTimeout
或SetInterval
;
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.