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

问题描述 投票:0回答:2

给出一个简单的HTTP调用:

object: Object;

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

我该如何修改它,以便每3秒钟用全新的数据刷新对象?

angular angular6
2个回答
0
投票
interval(3000).pipe( switchMapTo(this.http.get<any>( this._globals.apiServer + 'api/data', {responseType: 'json'})) ) .subscribe((resp: any) => { this.object = resp; })

notes:

    如果组件/服务被销毁,此可观察项需要取消订阅。
  1. 此操作将在3秒钟后开始,立即开始执行timer(0, 3000)代替


0
投票

如果您希望下一个请求在最后,使用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); } }
  • © www.soinside.com 2019 - 2024. All rights reserved.