我需要一个在角度2的计时器,它在一段时间间隔后滴答作响,并做一些任务(可能是调用一些函数)。
如何在Angular 2中做到这一点?
发布于 2017-05-11 15:09:07
import {Component, View, OnInit, OnDestroy} from "angular2/core";
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
})
export class NewContactComponent implements OnInit, OnDestroy {
ticks = 0;
private timer;
// Subscription object
private sub: Subscription;
ngOnInit() {
this.timer = Observable.timer(2000,5000);
// subscribing to a observable returns a subscription object
this.sub = this.timer.subscribe(t => this.tickerFunc(t));
}
tickerFunc(tick){
console.log(this);
this.ticks = tick
}
ngOnDestroy(){
console.log("Destroy timer");
// unsubscribe here
this.sub.unsubscribe();
}
}
发布于 2018-02-14 20:35:12
您可以简单地使用setInterval实用程序并使用箭头函数作为回调,这样this
就会指向组件实例。
对于ex:
this.interval = setInterval( () => {
// call your functions like
this.getList();
this.updateInfo();
});
在您的ngOnDestroy生命周期钩子中,清除间隔。
ngOnDestroy(){
clearInterval(this.interval);
}
发布于 2017-04-29 16:54:49
我遇到了一个问题,我不得不使用计时器,但我必须在同一时间,相同的屏幕上显示两个组件。我在服务中创建了timerObservable。我在两个组件中都订阅了计时器,然后发生了什么?它不会被同步,因为新的订阅总是创建自己的流。
我想说的是,如果您计划在多个地方使用一个计时器,请始终将.publishReplay(1).refCount()
放在观察者的末尾,因为它每次都会发布相同的流。
示例:
this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
return this.calculateTime(startDate);
}).publishReplay(1).refCount();
https://stackoverflow.com/questions/35813310
复制相似问题