我有一个 obsverable.timer 函数,可以创建一个倒数,我想调用一个称为 endTimer((的特定函数计时器已在我的@component内部结束,而无需使用settimeout((。我可以在视图中检查 counter == 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>
您在某个地方订阅吗?在带有"异步"管道左右的模板上?如果没有,您必须订阅它。出于同样的原因,变量" this.counter"将永远不会达到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 */})
}
希望这会有所帮助。