Angular:如何全局侦听路由器事件

时间:2017-11-03 17:30:20

标签: angular angular2-routing angular2-providers

我想在导航发生时显示微调器。如何全局监听路由器事件,以便我可以在NavigationStart上显示微调器,并在路由发生时将其隐藏在NavigationEnd上,就像我们如何处理HttpInterceptor全局拦截请求一样。

请给我一些建议。

1 个答案:

答案 0 :(得分:4)

这就是我使用的:

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

@Component({
    selector: 'mh-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
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;
        }
    }
}