簡體   English   中英

Angular 6,每隔幾秒調用一次 API 或每隔幾秒從訂閱接收新數據

[英]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;
})

筆記:

  1. 如果組件/服務被銷毀,則需要取消訂閱此 observable。

  2. 這將在 3 秒后開始,立即開始執行timer(0, 3000)代替

您可以使用SetTimeoutSetInterval

  • 如果您希望下一個請求在上次請求后恰好 3 秒執行,請使用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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM