Home > database >  use of async pipe in ngoninit
use of async pipe in ngoninit

Time:03-04

I have in my angular app many api calls, where I want to show a loading component, if data is coming from server.

For this I have a loader service like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class LoaderService {
  isLoading = new Subject<boolean>();

  show() {
    this.isLoading.next(true);
  }

  hide() {
    this.isLoading.next(false);
  }
}

I have an httpInterceptor too, where I use the show and hide methods like this:

intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this.loaderService.show();

    return new Observable((observer) => {
      next.handle(request).subscribe(
        (res) => {
          observer.next(res);
        },
        (err: HttpErrorResponse) => {
          this.loaderService.hide();
          if (err.error.message) {
            this.customNotificationService.showNotification(
              err.error.message,
              3000,
              'error'
            );
          } else {
            this.customNotificationService.showNotification(
              'Ismeretlen eredetű hiba. Lépj kapcsolatba a rendszer üzemeltetőjével.',
              3000,
              'error'
            );
          }
        },
        () => {
          this.loaderService.hide();
        }
      );
    });
  }

In the component, where I want to use the loading component, I have this in the template:

<loading-overlay
  [visible]="loadingOverlayVisible | async"
  loadingText=""
></loading-overlay>

And in the ts:

loadingOverlayVisible: Subject<boolean> = this.loaderService.isLoading;

This works except one case: ngOnInit. When the component loads, I load the initial data like this:

ngOnInit() {
    this.gridData = { data: [], total: 0 };
    this.userService.getUsers().subscribe((users) => {
      users.forEach((user) => {
        // we get this as string from the backend
        user.lastLoginDateDisplay = new Date(user.lastLoginDateDisplay!);
      });
      this.gridData = { data: users, total: users.length };
    });
  }

The data gets loaded, but without any loading indicator. If I change the logic and use the standard subscribe/unsubscribe way, it works. But it would be more cleaner/smarter with the async pipe.

So, the question is: how to do that?

CodePudding user response:

LoaderService.isLoading should be a BehaviorSubject instead. I'm not sure, but I think ngInit finishes before the template is first evaluated. If I'm right, then LoaderService.isLoading has already emitted true, and when your async pipe subscribes, it's too late.

  • Related