javascript - 如何在每个时间间隔都必须调用的角度实现轮询机制?
问题描述
如何在 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;
)
解决方案
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 - 如果需要,在析构函数上发出
推荐阅读
- vb.net - 如何在 vb.net 中设置按钮按下限制时间
- c# - 运行应用程序时未反映设计器对 winform gridview 的更改
- reactjs - 如何在 React 应用程序中仅加载 Redux Store 的一部分
- php - WooCommerce 开发工具/环境/调试器
- c - C - float** 函数参数不传递值
- unity3d - Unity GestureRecognizer ManipulationStarted 和 -updated 不起作用
- android - 谷歌登录失败
- laravel - 无法探测视频laravel ffmpeg
- java - 迭代反射的子类,变量似乎没有阴影,IntelliJ 似乎有冲突
- php - PHP,将表单数据插入 MYSQLi