Search code examples
angularangular-materialmat-table

Angular | Refresh table every 5 seconds with Timer


I am using material table in a page and I want it the table datasource to be refreshed every 5 seconds so that any change in values will be reflected in the table. This is what I've done now:

everyFiveSeconds: Observable<number> = timer(0, 5000);

ngOnInit() {
this.everyFiveSeconds.subscribe(() => {
  this.getComponents();
});

getComponents() sends a get request and paginates the output to a material table. However the problem is, once I load this page initially, the get request gets made every 5 seconds. But the application keeps sending the request even if I navigate to another page. If I revisit the page, the request gets sent every 2.5 seconds and the frequency of requests keep increasing if I repeat it.

How can I modify my code so that this get request is sent only when I am sitting at this component page and also make sure if I revisit this page, multiple timers are not getting created?


Solution

  • It's something like this:

    import { timer } from 'rxjs';
    
    export class MyClass implements OnInit, OnDestroy {
        subscription: Subscription;
        everyFiveSeconds: Observable<number> = timer(0, 5000);
        
         ngOnInit() {
          this.subscription = this.everyFiveSeconds.subscribe(() => {
             this.getComponents();
           });
         }
        }
        ngOnDestroy() {
          this.subscription.unsubscribe();
        }
    }