03 August 2021

Progressbar Loading Router Angular 2+

 

HTML

<ng-container *ngIf="loader$ | async as _loader">
  <ngb-progressbar
    class="loading-bar"
    height="3px"
    [value]="_loader"
  ></ngb-progressbar>
</ng-container>

TS

public loader$: Observable<number>;
private loaderSubject: BehaviorSubject<number> = new BehaviorSubject<number>(0);
private unsubscribe: Subscription[] = []; // Read more: => https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/
constructor(private router: Router) {
  this.loader$ = this.loaderSubject;
  // page progress bar percentage
  const routerSubscription = this.router.events.subscribe((event) => {
    if (event instanceof NavigationStart) {
      // set page progress bar loading to start on NavigationStart event router
      this.loaderSubject.next(10);
    }
    if (event instanceof RouteConfigLoadStart) {
      this.loaderSubject.next(65);
    }
    if (event instanceof RouteConfigLoadEnd) {
      this.loaderSubject.next(90);
    }
    if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
      // set page progress bar loading to end on NavigationEnd event router
      this.loaderSubject.next(100);
      if (this.routerLoaderTimout) {
        clearTimeout(this.routerLoaderTimout);
      }
      this.routerLoaderTimout = setTimeout(() => {
        this.loaderSubject.next(0);
      }, 300);
    }
  });
  this.unsubscribe.push(routerSubscription);
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang