Angular 2 resolver with loading indicator

yamidvo picture yamidvo · Feb 5, 2017 · Viewed 10.1k times · Source

I use resolvers to load the data into the components, but until the data is not returned from the server the component does not load. I would like to know if there is a way to render a load indicator before the server responds.

Answer

yaircarreno picture yaircarreno · Jun 9, 2017

You can use the "reacting to routing events" strategy that consist to implement the App to react when any routing event occurs. To do that, you will need in your app.component.ts some code like:

import { Component } from '@angular/core';
import { Router, RouterEvent, NavigationStart, NavigationEnd, NavigationError, NavigationCancel } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {

  loading: boolean = true;

  constructor(private router: Router) {
    router.events.subscribe((routerEvent: RouterEvent) => {
      this.checkRouterEvent(routerEvent);
    });
  }

  checkRouterEvent(routerEvent: RouterEvent): void {
    if (routerEvent instanceof NavigationStart) {
      this.loading = true;
    }

    if (routerEvent instanceof NavigationEnd ||
      routerEvent instanceof NavigationCancel ||
      routerEvent instanceof NavigationError) {
      this.loading = false;
    }
  }
}

And in the view(html) something like:

<div id="loader" class="myloader" *ngIf="loading">
  Loading...
</div>