I am trying to make a 5 mins countdown that triggers a service method and reloads the 5 mins countdown (basically I am trying to reload some data every 5 mins)
constructor(
private reloadDataService: ReloadDataService,
private userService: UserService
) {
this.timer$ = timer(0, 1000).pipe(
scan(acc => --acc, 300),
takeWhile(x => x >= 0),
);
}
realod method is trigger by a button or every 5 mins
reload() {
this.lastRefresh = new Date();
this.reloadDataService.reload()
}
ngOnInit() {
this.getUserDetails();
}
I have tried with
this.timer$ = timer(0, 1000).pipe(
switchMap(() => this.reload()),
scan(acc => --acc, 300),
takeWhile(x => x >= 0),
);
but didn't work - how can I trigger the reload method every 5 mins?
use the subscribe property of timer,
const source = timer(0, 300000);
source.subscribe((_) => this.reload());
Try below code. It will setup the the interval method and when subscribing to refreshInterval$ you can call reload method or any operation that you want to repeat.
const refreshInterval$: Observable<any> = timer(0, 300000)
.pipe(
// Boolean to kill the request if the user closes the component
takeWhile(() => this.killTrigger));
refreshInterval$.subscribe(() => {
// Your code here
});
One way is by using interval or timer function offered by rxjs.
Here is an example that I created.
countDown: Subscription = null;
minutes: number = 5;
counter: number = this.minutes * 60;
triggered: number = 0;
start timer function
startTimer(): void {
this.countDown ? this.stopTimer() : null;
this.countDown = interval(1000).subscribe(() => {
--this.counter;
if (!this.counter) {
this.trigger();
}
});
}
stop timer function
stopTimer(): void {
if (this.countDown) {
this.countDown.unsubscribe();
this.countDown = null;
}
}
trigger function that get executed when countdown finish
trigger(): void {
this.counter = this.minutes * 60;
this.stopTimer(); // unsubscribe timer
this.startTimer(); // re subscribe timer
this.triggered++;
// your code
}
I hope this helps you, let me know if you build another solution.
Best wishes,
Dev.klodian