亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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條經驗 獲得超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); 

  }


查看完整回答
反對 回復 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 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號