Call a function every x seconds in Angular


This is a quick solution to retrieve the results every x seconds or minutes.

It creates a subscription to a RxJS function timer. This function creates an Observable that emit a result after a certain time.

Example

To call the http request every 10 seconds:

import {Subscription, timer} from 'rxjs';  
 
timerSubscription: Subscription; 
  
 ngOnInit(): void { 
      // timer(0, 10000) call the function immediately and every 10 seconds 
      this.timerSubscription = timer(0, 10000).pipe( 
      map(() => { 
        this.loadData(); // load data contains the http request 
      }) 
    ).subscribe(); 
} 
     
// don't forget to unsubscribe when the Observable is not necessary anymore 
ngOnDestroy(): void { 
  this.timerSubscription.unsubscribe(); 
} 


WebApp built by Marco using SpringBoot, Java 17, Mustache, Markdown and in Azure