I need a timer to be reset which will be called after each activity. So I created a TimerService and setting the timer inside that.
TimerService class:
@Injectable()
export class TimerService {
timer: Observable<any>;
constructor() { }
setTimer(timerVal: number) {
this.timer = Observable.timer(timerVal);
}
}
Then I tried to subscribe to it and once the timer has lapsed, it should alert something. I put this logic in AppComponent since I need to subscribe to it in the Rootlevel.
AppComponent class:
export class AppComponent implements OnInit{
title = 'DataBox';
constructor(private timerService: TimerService){}
ngOnInit() {
this.timerService.setTimer(3000);
this.timerService.timer.subscribe(t => {
alert("hello");
})
}
}
Now I tried to update the value of the timer from another component, but the it does not affect the timer that is already set.
AnotherComponent class:
export class AnotherComponent implements OnInit{
users: Observable<any>;
constructor(private listUser: ListUserService, private timerService: TimerService) { }
ngOnInit() {
}
updateTimer() {
this.timerService.setTimer(5000);
}
}
How do I subscribe to a timerService and update the timer whenever I want? How do I create a Singleton Service and subscribe to the timer? But it should alert only when the timer expires and only once. I'm new to Angular, so pls bear with me.