【问题标题】:Ionic2/Angular 2 Observable.timer duplicateIonic2/Angular 2 Observable.timer 重复
【发布时间】:2017-09-06 17:33:56
【问题描述】:

我在 Ionic 2 项目中创建了一个 Observable.timer 来倒计时(例如 00:00:59->00:00:00)。例如,我在名为“PageB”的页面中创建了计时器,下面是打字稿代码:

export class PageB {
 constructor(){
this.timer = Observable.timer(500,500).map(i=>this.result-i*503).take((this.result-575999970)/503).subscribe(i => 
{
this.time=i;
console.log(i);
console.log(moment(this.time).format('HH:mm:ss'));
});
}
}

上述代码的Console.log输出:

但是,我遇到了一个问题,当我从 PageB 离开到上一页然后再次回到 PageB(PageB->上一页->PageB)时,这个计时器会重复。

重复的情况:


您可以看到 00:00:47、00:00:46 和其余部分重复了很多次。我不能在离开 PageB 时使用"this.timer.unsubscribe()" 来停止计时器,因为我需要它在后台继续倒计时。

因此,谁能告诉我如何解决这个问题?谢谢

【问题讨论】:

  • 这有点像在监视网络连接时发生的重复,其中事件触发了两次...针对该问题的建议是提供一个过滤触发事件的服务...stackoverflow.com/a/42454236/7266219不知道这是否会有所帮助..但看看。
  • 这似乎不适合我的问题......谢谢顺便说一句

标签: angular timer duplicates ionic2 observable


【解决方案1】:

您可以将 Observable 移至提供者并使用 Subject 确保只有一个计时器。

export class TimerProvider {
 constructor(){
}
timerSubject:Subject<any>;

loadTimer(){

Observable.timer(500,500).map(i=>this.result-i*503).take((this.result-575999970)/503).subscribe(i => 
{
this.timerSubject.next(i);
});
}

getTimer(){
 if(!this.timerSubject(){
   this.timerSubject = new Rx.Subject();
   this.loadTimer();
 }
 return timerSubject.asObservable();
}
}

在您的页面B中:

export class PageB {
 constructor(private timeProvider:TimerProvider){
this.timer = this.timeProvider.getTime().subscribe(i => 
{
this.time=i;
});
}
}

ngOnDestroy(){
   this.timer.unsubscribe();
}

只要您的提供程序是单例的,您就会有一个计时器,并且它将在第一次打开页面 B 时开始。

【讨论】:

  • 感谢您的回复。我试过空检查但还是不行......
  • 因为它是在构造函数中设置的..您的页面被创建了多次..可能将timer设置为静态? stackoverflow.com/questions/16462839/…
  • 它在使用空检查并将计时器设置为静态时起作用。但是,还有一个问题,当我离开PageB并返回时,我无法再次获取“this.time”变量的值,这意味着我只能在第1个页面B时获取“this.time”的值时间。
  • 所以在这种情况下,即使时间也需要是静态的.. 不确定它是否适合您的用例.. 或者可能将计时器移动到单例提供程序/app.component?
  • 如果我无法再次获得“this.time”,如果我离开PageB并返回,我将无法再次在PageB的UI上显示倒计时数字......
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 2016-07-19
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2018-02-01
相关资源
最近更新 更多