6

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?

renathy
  • 5,125
  • 20
  • 85
  • 149

6 Answers6

9

You could destroy interval on OnDestroy life cycle hook of the component.

Using clearInterval(this.interval)

ngOnDestroy() {
   if (this.interval) {
     clearInterval(this.interval);
   }
}
ptesser
  • 379
  • 4
  • 11
  • Seems similer answer of mine – Pardeep Jain Nov 27 '18 at 07:52
  • I know, because we wrote on the same time, more less. – ptesser Nov 27 '18 at 08:02
  • Btw, you could also mention that component should implement OnDestroy... otherwise ondestroy never called, right? – renathy Nov 27 '18 at 08:31
  • Yes, for the editor you should implements `OnDestroy` and it's the best approach. For the final result you could avoid it because at runtime Javascript lose interfaces declared with Typescript. But the best practice is to insert it. – ptesser Nov 27 '18 at 08:51
1

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.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
1

try this.

save: boolean = false;
autoSave() {
        setInterval(() => {
            console.log('setTimeOut');
            this.save = true;

        }, 1000);
}
Fahimeh Ahmadi
  • 813
  • 8
  • 13
0

try this.

routerOnActivate() {
   this.interval = setInterval(() => {
               this.refresh(); // api call
            }, 10000);
}

routerOnDeactivate() {
  clearInterval(this.interval);
}
Farhat Zaman
  • 1,339
  • 10
  • 20
0

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
}
lloydaf
  • 605
  • 3
  • 17
0

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

Ankit Choudhary
  • 145
  • 2
  • 13