【问题标题】:Not able to clear my setInterval in Ionic无法在 Ionic 中清除我的 setInterval
【发布时间】:2020-10-22 17:22:51
【问题描述】:

我有一个 IONIC 4 应用程序,我需要每 20 秒调用一次 api,如果用户移动到其他页面需要停止调用该 api。我能够每 20 秒进行一次 api 调用,但当我移动到其他页面时无法停止它。下面是我的代码,请问我哪里出错了?

 rateTimer:any;

constructor(private loginServiceService: LoginServiceService) {
    this.loginServiceService.getappData();

    this.rateTimer=setInterval(() => { 
      this.loginServiceService.getappData(); 
   }, 10000);
   }

// When I move to other page, I clear the setInterval from here

 ngOnDestroy() {
    clearInterval(this.rateTimer);
  }

【问题讨论】:

标签: javascript angular ionic-framework ionic4 angular8


【解决方案1】:

据我所知,Ionic 有一个用于页面导航的缓存,这就是为什么ngOnDestroy/ngOnInit 并不总是有效的原因。但是,一旦当前页面被移开,ionViewDidLeave 肯定会触发(有关更多详细信息,请参阅https://ionicframework.com/docs/api/router-outlet#life-cycle-hooks):

export class YourComponent {
  ionViewDidLeave() {
    // Do actions here
  }
}

【讨论】:

  • 所以如果你在ionViewDidLeave 中使用console.log() 你什么也看不到,或者只是间隔没有被清除?
  • 问题是当我使用 ionViewDidLeave 时我没有到达那里,但是当我使用 ngOnDestroy 时我确实得到了调试器。这里的问题是我偶尔会受到打击,而不是每次
  • 为什么我没有被 ionViewDidLeave 击中?任何线索
  • 奇怪,老实说我不知道​​ - 也许你会在这篇文章中找到一些有用的信息:medium.com/@paulstelzer/…
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多