首页 > 解决方案 > 如何在每个时间间隔都必须调用的角度实现轮询机制?

问题描述

如何在 Angular 中实现轮询机制?

我有一个 API 调用来订阅,其中包含数据、再次调用它的时间间隔(以毫秒为单位)以及必须停止调用之后的完成标志。

在第一次调用 API 时,我们在 result 中获取数据,在 result[0].requestInterval 中获取调用 API 的间隔,在 result[0].requestComplete 中获取停止调用 API 的标志,如果为真,我们必须停止调用 API 否则再次调用 API

this.bookFlightService.GetFlights(this.baseUrl, searchResource, inboundDate)
            .subscribe(result => {
                this.callNo++;
                this.bookFlights = result as BookFlights[];
                this.requestComplete = this.bookFlights[0].complete;
                this.requestInterval = this.bookFlights[0].callAfterMs;
)

标签: javascriptangularangular6observableangular7

解决方案


destructor$ = new Subject();

this.bookFlightService.GetFlights(this.baseUrl, searchResource, inboundDate).pipe(
  switchMap(response => timer(0, 1000)),
  tap(() => this.callNo++),
  switchMap(() => this.makeHttpCall()),
  takeUntil(this.destructor$),
  tap(response => { if(response.complete) this.destructor$.next(); }),
).subscribe(response => console.log(response));

1 - 创建一个主题以在需要时停止流
2 - 第一次进行 Http 调用
3 - 将流更改为计时器(发出一次,然后每隔给定的毫秒)
4 - 增加调用次数(原始代码)
5 - 再次将您的计时器流切换到 API 的新调用
6 - 直到主题发出 7 - 如果需要,在析构函数上发出

演示堆栈闪电战


推荐阅读