在Ionic 2中为Observable.timer创建回调

时间:2018-03-26 07:21:01

标签: angularjs ionic-framework ionic2

我有一个 Observable.timer 函数可以创建一个倒计时器,当我的@Component结束时,我想调用一个名为 endTimer()的特定函数使用setTimeout()。我可以在视图中检查计数器== 0 的值,但如何检查@Component

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

//imported pipes
import {FormatTimer} from '../../pipes/formattimer';

@Component({
  selector: 'page-livegame',
  templateUrl: 'livegame.html',
  pipes: [FormatTimer]
})
export class LivegamePage {

  gamesData: any;
  countDown: any;
  counter = 1*60;
  tick = 1000;

  constructor(public modalCtrl: ModalController, public navCtrl: NavController, public navParams: NavParams, public storage: Storage) {
    //setTimeout(function(){ endTimer(); }, 300000);
  }

  ionViewDidLoad() {
    this.getCurrentGame();
  }

  ngOnInit() {
    this.countDown = Observable.timer(0, this.tick)
      .take(this.counter)
      .map(() => --this.counter);
  }

  endTimer() {
     console.log('ended');
  }

}
  

<div *ngIf="counter == 0">the timer has ended </div>

1 个答案:

答案 0 :(得分:0)

你是订阅吗?在模板上使用&#39; async&#39;管子还是这样?如果没有,您必须订阅它。出于同样的原因,变量&#39; this.counter&#39;永远不会达到0。

如果您已使用异步管道在模板上订阅它,则可以最终使用该运算符:

  ngOnInit() {
     this.countDown = Observable.timer(0, this.tick)
       .take(this.counter)
       .map(() => --this.counter)
       .finally(() => this.endTimer())
  }

如果您没有在模板上订阅它,您可以这样订阅:

ngOnInit() {
     this.countDown = Observable.timer(0, this.tick)
       .take(this.counter)
       .map(() => --this.counter)
       .finally(() => this.endTimer())
       .share() // Avoid multiple side effect if multiple subscribers

     this.countDown.subscribe(() => { /* do nothing */})
  }

希望这有帮助。