KrisG
KrisG

Reputation: 1091

Show Loading Indicator for a timer based observable rendered using async pipe

I have an angular http request which I have made auto refresh using rxjs timer...

this.data$ = timer(0, 1000 * 10).pipe(
  flatMap(() => this.service.getData())
);

I am showing this observable in my template using async pipe within an if else to show a loading indicator before it completes...

<ng-container *ngIf="data$ | async as data; else loading">
</ng-container>

<ng-template #loading>
  <ngx-spinner></ngx-spinner>
</ng-template>

This works great. But when the timer triggers every 10 seconds I would like the loading template to show again until the http request completes. I would guess I need a way to form this rxjs expression so that every 10 seconds it immediately emits a null or something then executes the request and then emits the request response object.

Upvotes: 1

Views: 376

Answers (1)

martin
martin

Reputation: 96889

If you don't mind discarding the previously loaded result while it's loading you can emit null before triggering the request:

this.data$ = timer(0, 1000 * 10).pipe(
  flatMap(() => concat(of(null), this.service.getData())),
);

Upvotes: 2

Related Questions