首页 > 解决方案 > 使用 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);   
}

标签: javascriptangularsetinterval

解决方案


您可以尝试使用 RxJS和(或根据您的要求)运算符来连续轮询端点,而不是依赖setInterval()or函数。尝试以下setTimeout()repeatdelaytakeUntiltakeWhile

一些服务

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();
  }
}

推荐阅读