setInterval,clearInterval实例超出范围

时间:2018-02-05 00:25:02

标签: typescript ionic3 setinterval

在Ionic3中,我创建了一个刷新数据的间隔,我希望它在离开视图时停止。但我一直无法确定区间实例的范围...... 请注意,这是我在打字稿中的第一步......

updateData(){    
  var interval = setInterval(() => {
    this.getdata.getData().subscribe( data => {
      this.channels = data.channels;
    })
  },2000);
}

ionViewWillLeave() {
  clearInterval(interval);//[TS]Cannot find name 'interval'
  console.log('leave view');
}

2 个答案:

答案 0 :(得分:2)

这是完整的Observable解决方案

subscription: Subscription;

updateData(){
    const interval = Rx.Observable.interval(2000).flatMap(() => this.getdata.getData());
    subscription = interval.subscribe(data => { this.channels = data.channels; });
}

ionViewWillLeave() {
    subscription.unsubscribe();
    console.log('leave view');
}

当你使用Observable时,通常很好地使用它

答案 1 :(得分:1)

只需将变量移动到外部范围,例如

interval: number; // Moved it out. 

updateData(){    
  this.interval = setInterval(() => {
    this.getdata.getData().subscribe( data => {
      this.channels = data.channels;
    });
  },2000);
}

ionViewWillLeave() {
  clearInterval(this.interval);
  console.log('leave view');
}