简体   繁体   中英

refreshing data on page every X seconds for angular 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?

You 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.

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
}

try this.

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

        }, 1000);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM