I need to refresh data of angular component each 30 seconds. I use simple setInterval
:
this.interval = setInterval(() => {
this.refresh(); // api call
}, 10000);
However, this is incorrect, because even when I navigate to another "page" (in angular SPA everything is one page, so it is not really another page), refresh is happening each 30 seconds.
What is the correct way to refresh data every 30 seconds only when on specific page/component?
I need to refresh data of angular component each 30 seconds. I use simple setInterval
:
this.interval = setInterval(() => {
this.refresh(); // api call
}, 10000);
However, this is incorrect, because even when I navigate to another "page" (in angular SPA everything is one page, so it is not really another page), refresh is happening each 30 seconds.
What is the correct way to refresh data every 30 seconds only when on specific page/component?
Share Improve this question asked Nov 27, 2018 at 7:45 renathyrenathy 5,35520 gold badges91 silver badges155 bronze badges 1- This article will help you : stackoverflow.com/questions/44947551/… – Joel Joseph Commented Nov 27, 2018 at 7:48
6 Answers
Reset to default 11You could destroy interval on OnDestroy
life cycle hook of the component.
Using clearInterval(this.interval)
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
You could clearInterval in ngOnDestroy
life cycle hook of component
ngOnDestroy() {
clearInterval(this.interval);
}
ngOnDestroy
will call every time component destroy in digest cycle and it will clear your interval as well (If you do so). Generally used to call logic which we don't require after navigation of current route to another.
try this.
save: boolean = false;
autoSave() {
setInterval(() => {
console.log('setTimeOut');
this.save = true;
}, 1000);
}
try this.
routerOnActivate() {
this.interval = setInterval(() => {
this.refresh(); // api call
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.interval);
}
When you navigate to another page, you have to clear the interval you are setting.
this.interval = setInterval(()=>{
...
});
navigateToAnotherPage = () => {
//function to navigate to another page
clearInterval(this.interval);
router.navigate(...)//if you are using router to navigate
}
You can also leverage reactive style.
import { timer } from 'rxjs';
/*
timer takes a second argument, how often to emit subsequent values
in this case we will emit first value after 1 second and subsequent
values every 2 seconds after
*/
const source = timer(0, 2000);
//output: 0,1,2,3,4,5......
const subscribe = source.subscribe(val => console.log(val));
Reference - https://www.learnrxjs.io/learn-rxjs/operators/creation/timer