Call a function every 10 seconds Angular2

后端 未结 5 2092
臣服心动
臣服心动 2020-12-05 07:18

I\'m trying to create a Timer that calls an API call every 10 seconds, I\'m using setTimeOut but the thing is that it becomes an infin

5条回答
  •  一向
    一向 (楼主)
    2020-12-05 07:40

    Use observable.timer for your purpose in angular way.

     export class CurrentRunsComponent implements OnInit, OnDestroy {
      private timer;
    
    
      ngOnInit() {
        this.timer = Observable.timer(10000);
        this.timer.subscribe((t) => this.onTimeOut());
      }
       onTimeOut() {
        this.ApiCall().then(
        success => {
        if(success ['ok'] == 0){
            this.navCtrl.push(myPage);
        }
        },
        error => { console.log(error); });
    }
    
       ngOnDestroy(){
        console.log("Destroy timer");
    
      }
    }
    

提交回复
热议问题