Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show loading indicator in Angular while waiting for a RxJS observable

I have an Angular component that listens for a route parameter for a user id to change and when it does it loads the user details. The user details takes a few seconds to return data from the API.

If i'm viewing details for User A and then click to view details on User B, it continues to show User A until User B details are returned a few seconds after my click. Is there a way I can show a loading indicator or just blank it out while it's retrieving data for User B?

User details component:

ngOnInit(): void {
  this.userDetails = this.route.paramMap.pipe(
    switchMap((params: ParamMap) => this.userService.getUserDetails(+params.get('userId')))
  );
}

User details template:

<div *ngIf="userDetails | async as userDetails">
  <h1>{{userDetails.firstName}} {{userDetails.lastName}}</h1>
</div>

I would like the user details div to either be blank or show some sort of loading indicator if that inner switchMap is currently running. I know one option would be to have a loading variable that I set to true before the switchMap and false after the switchMap and use that in the *ngIf of the div, but I'm hoping there was a slicker way to not have to have loading variables for EVERY one of these situations.

I have an example StackBlitz: https://stackblitz.com/edit/angular-ng-busy-yxo1gu

The goal is when I click the User B button, User A information should disappear while User B is loading. I have dozens of this scenario in my app so I'm looking for the cleanest way to do this.

like image 997
Jeremy Avatar asked Dec 13 '18 18:12

Jeremy


People also ask

What does .subscribe return in Angular?

Subscribinglink An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Returns an Observable instance that synchronously delivers the values provided as arguments.

Why do we call observables as lazy?

Observables are "lazy", meaning if no one is listening, nothing happens.

Does pipe return observable?

The pipe() function takes one or more operators and returns an RxJS Observable. pipe can be used as a standalone method, which helps Angular developers reuse it at multiple places or as an instance method. This article will explain what pipe is and how to use it in an Angular Application.


1 Answers

you can change your *ngIf

ngIf="userDetails | async as userDetails else #loading"

then

<div #loading>
  loading...
</div>

Reference

like image 86
Derviş Kayımbaşıoğlu Avatar answered Oct 29 '22 10:10

Derviş Kayımbaşıoğlu