Javascript 如何在angular2中创建计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35813310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create timer in angular2
提问by kuntal
I need a timer in Angular 2, which tick after a time interval and do some task (may be call some functions).
我需要一个 Angular 2 中的计时器,它在一个时间间隔后打勾并执行一些任务(可能会调用一些函数)。
How to do this with Angular 2?
如何使用 Angular 2 做到这一点?
回答by Abdulrahman Alsoghayer
In Addition to all the previous answers, I would do it using RxJS Observables
除了之前的所有答案,我还会使用 RxJS Observables
please check Observable.timer
Here is a sample code, will start after 2 seconds and then ticks every second:
这是一个示例代码,将在 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);
}
}
And here is a working plunker
这是一个工作的plunker
UpdateIf you want to call a function declared on the AppComponent class, you can do one of the following:
更新如果要调用在 AppComponent 类上声明的函数,可以执行以下操作之一:
** Assuming the function you want to call is named func,
** 假设您要调用的函数名为func,
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(this.func);
}
The problem with the above approach is that if you call 'this' inside func, it will refer to the subscriber object instead of the AppComponent object which is probably not what you want.
上述方法的问题在于,如果您在 func 中调用“this”,它将引用订阅者对象而不是 AppComponent 对象,这可能不是您想要的。
However, in the below approach, you create a lambda expression and call the function funcinside it. This way, the call to func is still inside the scope of AppComponent. This is the best way to do it in my opinion.
但是,在下面的方法中,您创建了一个 lambda 表达式并在其中调用了func 函数。这样,对 func 的调用仍然在 AppComponent 的范围内。在我看来,这是最好的方法。
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
check this plunkerfor working code.
检查此 plunker以获取工作代码。
回答by Philip
Another solution is to use TimerObservable
另一种解决方案是使用 TimerObservable
TimerObservableis a subclass of Observable.
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();
}
}
P.S.: Don't forget to unsubsribe.
PS:不要忘记退订。
回答by Unnikrishnan Parameswaran
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();
}
}
回答by Shivang Gupta
You can simply use setInterval utility and use arrow function as callback so that this
will point to the component instance.
您可以简单地使用 setInterval 实用程序并使用箭头函数作为回调,以便this
指向组件实例。
For ex:
例如:
this.interval = setInterval( () => {
// call your functions like
this.getList();
this.updateInfo();
});
Inside your ngOnDestroy lifecycle hook, clear the interval.
在 ngOnDestroy 生命周期钩子中,清除间隔。
ngOnDestroy(){
clearInterval(this.interval);
}
回答by Matt Saunders
With rxjs 6.2.2 and Angular 6.1.7, I was getting an "Observable.timer is not a function" error.
使用 rxjs 6.2.2 和 Angular 6.1.7,我收到“Observable.timer 不是函数”错误。
This was resolved by replacing "Observable.timer" with "timer":
这是通过用“计时器”替换“Observable.timer”来解决的:
import { timer, Subscription } from 'rxjs';
private myTimerSub: Subscription;
ngOnInit(){
const ti = timer(2000,1000);
this.myTimerSub = ti.subscribe(t => {
console.log("Tick");
});
}
ngOnDestroy() {
this.myTimerSub.unsubscribe();
}
回答by xyztdanid4
I faced a problem that I had to use a timer, but I had to display them in 2 component same time, same screen. I created the timerObservable in a service. I subscribed to the timer in both component, and what happened? It won't be synched, cause new subscription always creates its own stream.
我遇到了一个问题,我必须使用计时器,但我必须在同一屏幕上同时在 2 个组件中显示它们。我在服务中创建了 timerObservable。我订阅了两个组件中的计时器,发生了什么?它不会被同步,因为新订阅总是会创建自己的流。
What I would like to say, is that if you plan to use one timer at several places, always put .publishReplay(1).refCount()
at the end of the Observer, cause it will publish the same stream out of it every time.
我想说的是,如果您计划在多个地方使用一个计时器,请始终放在.publishReplay(1).refCount()
观察者的末尾,因为它每次都会从中发布相同的流。
Example:
例子:
this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
return this.calculateTime(startDate);
}).publishReplay(1).refCount();
回答by Simon_Weaver
Found a npm package that makes this easy with RxJS as a service.
找到了一个 npm 包,它使 RxJS 作为服务变得容易。
https://www.npmjs.com/package/ng2-simple-timer
https://www.npmjs.com/package/ng2-simple-timer
You can 'subscribe' to an existing timer so you don't create a bazillion timers if you're using it many times in the same component.
您可以“订阅”现有计时器,因此如果您在同一组件中多次使用它,则不会创建无数个计时器。
回答by Alexis Poo
If you look to run a method on ngOnInit you could do something like this:
如果你想在 ngOnInit 上运行一个方法,你可以这样做:
import this 2 libraries from RXJS:
从 RXJS 导入这 2 个库:
import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";
Then declare timer and private subscription, example:
然后声明定时器和私有订阅,例如:
timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;
Last but not least run method when timer stops
最后但并非最不重要的计时器停止时运行方法
ngOnInit() {
this.subscription = this.timer.subscribe(ticks=> {
this.populatecombobox(); //example calling a method that populates a combobox
this.subscription.unsubscribe(); //you need to unsubscribe or it will run infinite times
});
}
That's all, Angular 5
就是这样,Angular 5
回答by Nazmul Nadim
Set Timer and auto call service after certain time
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}
getNotifications() {
setInterval(() => {this.getNewNotifications();
}, 60000); // 60000 milliseconds interval
}
getNewNotifications() {
this.notifyService.getNewNotifications().subscribe(
data => { // call back },
error => { },
);
}