Show activity Indicator while loading a lazy loaded Module in Angular 2

前端 未结 5 1028
后悔当初
后悔当初 2020-12-13 04:06

My scenario is as follows. I have a menu, with multiple options. Each menu should be shown depending on user permissions (already solved), most menu items are encapsulated a

5条回答
  •  感情败类
    2020-12-13 04:44

    You can listen for two router events:

    • RouteConfigLoadStart
    • RouteConfigLoadEnd

    They fire when a lazy loaded module is being loaded. The advantage of using these over the standard router events such as NavigationStart is that they won't fire on every route change.

    Listen to them in your root AppComponent to show / hide your spinner.

    app.component.ts

    import { Router, RouteConfigLoadStart, RouteConfigLoadEnd } from '@angular/router';
    
    ...
    
    export class AppComponent implements OnInit {
    
        loadingRouteConfig: boolean;
    
        constructor (private router: Router) {}
    
        ngOnInit () {
            this.router.events.subscribe(event => {
                if (event instanceof RouteConfigLoadStart) {
                    this.loadingRouteConfig = true;
                } else if (event instanceof RouteConfigLoadEnd) {
                    this.loadingRouteConfig = false;
                }
            });
        }
    }
    

    app.component.html

    Just a simple string here, but you could use a spinner component.

    
    
    Loading route config...
    

    I'm using this approach with Angular v4.2.3

提交回复
热议问题