I need a timer in Angular 2, which tick after a time interval and do some task (may be call some functions).
How to do this with Angular 2?
See Question&Answers more detail:osI need a timer in Angular 2, which tick after a time interval and do some task (may be call some functions).
How to do this with Angular 2?
See Question&Answers more detail:osIn Addition to all the previous answers, I would do it using RxJS Observables
please check Observable.timer
Here is a sample code, will start after 2 seconds and then ticks every second:
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
Update If you want to call a function declared on the AppComponent class, you can do one of the following:
** Assuming the function you want to call is named 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.
However, in the below approach, you create a lambda expression and call the function func inside 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.
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
check this plunker for working code.