renathy
renathy

Reputation: 5355

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?

Upvotes: 7

Views: 17136

Answers (6)

Ankit Choudhary
Ankit Choudhary

Reputation: 155

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

Upvotes: 0

Fahimeh Ahmadi
Fahimeh Ahmadi

Reputation: 1029

try this.

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

        }, 1000);
}

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

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.

Upvotes: 1

lloydaf
lloydaf

Reputation: 605

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
}

Upvotes: 0

ptesser
ptesser

Reputation: 399

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

Using clearInterval(this.interval)

ngOnDestroy() {
   if (this.interval) {
     clearInterval(this.interval);
   }
}

Upvotes: 11

Farhat Zaman
Farhat Zaman

Reputation: 1369

try this.

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

routerOnDeactivate() {
  clearInterval(this.interval);
}

Upvotes: 0

Related Questions