Angular 2 resolver with loading indicator

2019-03-15 23:38发布

问题:

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.

回答1:

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, Event, 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: Event) => {
      this.checkRouterEvent(routerEvent);
    });
  }

  checkRouterEvent(routerEvent: Event): 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>


回答2:

the simplest version is going to be an ngIf statement

wrap an image in an ngIf on a root level component.

use a service to set whether it is visible or not.

eg:

before sending request: call service function to set variable to true

then in the component that is loaded, have the first thing that it does is set that variable back to false



回答3:

You should use https://www.npmjs.com/package/angular2-busy

which Directly listen to your Api call

ngOnInit() {
        this.busy = this.http.get('...').subscribe();
    }

<div [ngBusy]="busy"></div>

This will show spinner until you get response from server.