Refresh Observable after API is recalled

Viewed 25

Im having an Observable that is storing data from an API.

  countDownLogout$: Observable<any> = this.authenticationService
    .getCountdown()
    .pipe(
      tap((x) => {  
        console.log('calling the service');
      setTimeout(() => {
        this.authenticationService.getCountdown().subscribe();
        }, 20000);
        
   
      
      })
 <ng-container *ngIf="countDownLogout$ | async as countDownLogout">

The API is called but observable and as result data and console log are not fired. Except from the first time.

I would like the observable to re-take the data after re-calling the API.

1 Answers

It doesn't work because that is not how you should do that.

Use this approach instead.


countdownLogout$ = timer(0, 20000).pipe(
  tap((i) => console.log('Calling the service for the ' + i + 'nth time')),
  switchMap(() => this.authenticationService.getCountdown())
);

Be careful to unsubscribe properly from this observable, otherwise you will have memory leaks !

Related