为了账号安全,请及时绑定邮箱和手机立即绑定

使用 setInterval() 的 HTTP 轮询每 1 秒调用一次,而不是提到的间隔

使用 setInterval() 的 HTTP 轮询每 1 秒调用一次,而不是提到的间隔

波斯汪 2022-10-27 15:57:38
我的 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);   }
查看完整描述

3 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

您可以尝试使用 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();

  }

}


查看完整回答
反对 回复 2022-10-27
?
qq_遁去的一_1

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

  }


查看完整回答
反对 回复 2022-10-27
?
慕工程0101907

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

  })();


查看完整回答
反对 回复 2022-10-27
  • 3 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信