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條經驗 獲得超8個贊
我通過在開始新間隔之前清除 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);
})();
添加回答
舉報