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?
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?
With rxjs 6.2.2 and Angular 6.1.7, I was getting an:
Observable.timer is not a function
error. This was resolved by replacing Observable.timer with 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();
}
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 => { },
);
}
on the newest version of Angular (I work on 12.2.*) Observable.timer is not supported. You can use it with a bit change at @Abdulrahman Alsoghayer example.
import {Component} from '@angular/core';
import {timer} from 'rxjs';
@Component({
selector: 'my-app',
template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
ticks =0;
ngOnInit(){
let timer$ = timer(2000,1000);
timer$.subscribe(t=>this.ticks = t);
}
}