从服务器端接收到值后停止 setinterval

Stop setinterval after receiving value from server side

我正在研究 ionic 4 和 angular。我的应用程序符合航班时刻表。我想做的是在特定航班到达时从我的服务器接收本地通知。 l 使用setInterval重新加载服务器以检查航班是否到达。问题是当航班到达时 setInterval 仍在重新加载,我也使用了 clearInterval 但没有停止。

 async ActiveNotif() {

   this.ng.run(() => {
      // reloading 
      this.interval= setInterval(()=>{

        this.http.get('flight=' + this.id + '', {}, {})
        .then(data => {

          let FlightDetails = JSON.parse(data.data);
          this.identification = FlightDetails.identification.callsign;
          this.Fstatus = FlightDetails.status.generic.status.text;
          console.log(this.Fstatus)

        });

        //checking

        if (this.Fstatus == "landed") {

          this.localNotifications.schedule(
            [
              {
                id:0,
                title: 'Your flight has arrived',
                text: 'Your flight ' + this.identification + 'is arrived',
                trigger: { count: 1 },
                sound: "file://assets/one.mp3"
              },


            ]);
        }

      },10000)

      if (this.Fstatus == "landed") {


        clearInterval(this.interval)

      }

    })


  } 

clearInterval 子句应该在您的 interval 中,以便定期调用 if 并产生 get 结果 :)

试试这个解决方案。尝试像我一样制作 set intervalclear interval
查看解决方案。

async ActiveNotif() {

   this.ng.run(() => {
      // reloading 
      var time = setInterval(callingFunction , 10000);
      function callingFunction(){
        this.http.get('flight=' + this.id + '', {}, {})
        .then(data => {

            let FlightDetails = JSON.parse(data.data);
            this.identification = FlightDetails.identification.callsign;
            this.Fstatus = FlightDetails.status.generic.status.text;
            console.log(this.Fstatus)

        });



        if (this.Fstatus == "landed") {

            this.localNotifications.schedule(
                [
                {
                    id:0,
                    title: 'Your flight has arrived',
                    text: 'Your flight ' + this.identification + 'is arrived',
                    trigger: { count: 1 },
                    sound: "file://assets/one.mp3"
                },


                ]);
        }           
      if (this.Fstatus == "landed") {


        clearInterval(time)

      }
      }
   })
}

http.get 是可观察的,而不是承诺。您需要订阅,而不是使用 "then"。如果使用httpClient,则不需要"parser",数据变为json还

顺便说一句,我更喜欢 'rxjs' 计时器,并使用 takeWhile 停止,并使用 switchMap 获取响应

this.dataReaded=false;
timer(0,1000).pipe(
   takewhile(()=>!this.dataReaded),
   switchMap(()=>{
      return this.httpClient.get('flight=' + this.id + '', {}, {})
   }))
   .subscribe(res=>{
       const FlightDetails = data.data;
       this.identification = FlightDetails.identification.callsign;
       this.Fstatus = FlightDetails.status.generic.status.text;
       this.dataReaded=true;
   })