我的 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);
}
在 repeatInterval 中调用 getApiData,并将 repeatInterval 作为 IIFE
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;
})
}
(repeatInterval(){
this.rateTimer=setInterval(() => {
this.getApiData();
}, 20000);
})();
与其依赖setInterval()
或setTimeout()
函数,不如尝试使用 RxJSrepeat
、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();
}
}
我通过在开始使用新间隔之前清除 SetInterval 来解决此问题,以避免间隔重复。
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(){
clearInterval(this.rateTimer);
this.rateTimer=setInterval(() => {
this.getApiData();
}, 20000);
}
首先尝试这样。
var rateTimer;
rateTimer = setInterval(() => {
console.log("Hello");
}, 5000);