如何在angular2中创buildTimer

您好想要一个在angular2计时器。 这是一段时间后打勾,并做一些任务(可能会调用一些function)。

如何做到这一点与angular2?

除了所有以前的答案,我会用RxJS Observables来做

请检查Observable.timer

这里是一个示例代码,将在2秒后开始,然后每秒钟打勾:

import {Component} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'my-app', template: 'Ticks (every second) : {{ticks}}' }) export class AppComponent { ticks =0; ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=>this.ticks = t); } } 

这里是一个工作的重要人物

更新如果你想调用一个在AppComponent类中声明的函数,你可以执行以下操作之一:

**假设您要调用的函数名为func

 ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(this.func); } 

上述方法的问题是,如果你在func里面调用'this',它会引用订阅者对象,而不是AppComponent对象,这可能不是你想要的。

但是,在下面的方法中,您创build一个lambdaexpression式并在其中调用函数func 。 这样,对func的调用仍然在AppComponent的范围内。 这是我认为最好的方法。

 ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=> { this.func(t); }); } 

检查这个笨蛋的工作代码。

另一个解决scheme是使用TimerObservable

TimerObservable是Observable的子类。

 import {Component, OnInit, OnDestroy} from '@angular/core'; import {Subscription} from "rxjs"; import {TimerObservable} from "rxjs/observable/TimerObservable"; @Component({ selector: 'app-component', template: '{{tick}}', }) export class Component implements OnInit, OnDestroy { private tick: string; private subscription: Subscription; constructor() { } ngOnInit() { let timer = TimerObservable.create(2000, 1000); this.subscription = timer.subscribe(t => { this.tick = t; }); } ngOnDestroy() { this.subscription.unsubscribe(); } } 

PS:别忘了忘记。

 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(); } } 

我遇到了一个问题,我不得不使用一个计时器,但我不得不在两个组件相同的时间,相同的屏幕上显示它们。 我在一个服务中创build了timerObservable。 我在这两个组件订阅了计时器,发生了什么? 它不会被同步,导致新的订阅总是创build自己的stream。

我想说的是,如果你打算在几个地方使用一个定时器,总是把.publishReplay(1).refCount()放在Observer的末尾,因此每次都会发布相同的stream。

例:

 this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => { return this.calculateTime(startDate); }).publishReplay(1).refCount(); 

find一个NPM包,使RxJS作为一项服务变得简单。

https://www.npmjs.com/package/ng2-simple-timer

你可以'订阅'一个现有的计时器,所以如果你在同一个组件中多次使用它,你不会创build一个bazillion计时器。