Angular6、每隔几秒调用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 observable 并关闭它。

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);
    }
}