3 回答
TA贡献1804条经验 获得超8个赞
您可以尝试使用 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();
}
}
TA贡献1725条经验 获得超7个赞
我通过在开始新间隔之前清除 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);
}
TA贡献1887条经验 获得超5个赞
在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);
})();
添加回答
举报