javascript - 使用 setInterval() 的 HTTP 轮询每 1 秒调用一次,而不是提到的间隔
问题描述
我的 Ionic 4 应用程序有一个要求,我需要每 20 秒调用一次 API。当我使用setInterval()
它时,API 每 1 秒而不是 20 秒命中一次。这是我的代码,我可以知道出了什么问题吗?
我的.ts文件
getApiData(){
this.http.get('https://kairavforex.com/api/libor_rate/',{},{'Content-Type': 'application/json','Authorization': "Token" + " " + this.authToken})
.then(data=>{
this.getData=JSON.parse(data.data).results;
})
this.repeatInterval();
}
repeatInterval(){
this.rateTimer=setInterval(() => {
this.getApiData();
}, 20000);
}
解决方案
您可以尝试使用 RxJS和(或根据您的要求)运算符来连续轮询端点,而不是依赖setInterval()
or函数。尝试以下setTimeout()
repeat
delay
takeUntil
takeWhile
一些服务
stopPolling$ = new Subject();
getApiData(): Observable<any> {
return this.http.get(
'https://kairavforex.com/api/libor_rate/',
{},
{'Content-Type': 'application/json','Authorization': "Token" + " " + this.authToken}
).pipe(
tap(data => this.getData = JSON.parse(data.data).results),
delay(20000), // <-- poll frequency
repeat(), // <-- poll till `stopPolling$` emits
takeUntil(stopPolling$) // <-- emit `stopPolling$` to stop polling
);
}
stopPollingApi() {
this.stopPolling$.next();
this.stopPolling$.complete();
}
一些组件
ngOnInit() {
this.someService.getApiData().subscribe( // <-- will start polling
res => { },
err => { }
);
}
someOtherFunc() { // <-- call this function to stop polling
if(someCondition) {
this.someService.stopPollingApi();
}
}
推荐阅读
- json - 如何使用 JSON 文件中的 Angular 7 中的插值来提供 SVG 图标?
- android - 从异步调用填充的 Flutter 列表会引发应用内错误,但不会崩溃
- ssl-certificate - macOS Mojave 升级后 Marklogic WebDav 服务器连接不工作
- python - sounddevice 多输入输出通道接线
- maven - 从命令行运行单个 TestNG 测试类的故障排除
- python - 如何遍历数据框并仅遍历唯一值?
- pygame - 你如何解决:pygame中的“TypeError:'Mob'对象不可下标”?
- linux - 命名信号量的 sem_open 失败,因为我的进程无法在 /dev/shm 中创建相关文件
- javascript - 服务器正在尝试将 HTML 表中的中继器控件转换为 HtmlTableRow
- typescript - 谷歌云函数错误“加载用户代码时函数失败。” 带有打字稿功能