1

I want to show a spinner whenever navigation occurs. How can I listen to router events globally so that I can show spinner on NavigationStart and hide it on NavigationEnd whenever routing occurs, like how we do with HttpInterceptor for globally intercepting requests.

Please give me some suggestions.

karthikaruna
  • 3,042
  • 7
  • 26
  • 37

1 Answers1

8

This is what I use:

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;
        }
    }
}
DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • 1
    Personally, I would move this logic into a service which exposes an observable. – Jota.Toledo Nov 03 '17 at 18:12
  • 1
    It is already provided as a service that already exposes an observable. I'd be curious about the benefits of wrapping it in another service? – DeborahK Nov 03 '17 at 19:31
  • @DeborahK Maybe a benefit is the logic of the navigation listener is not part of appComponent and maybe if you want to add other "Global listener" at App Component is better separate logic otherwise you will have checkRouterEvent method, NoRelatedRouterLogicListener method, N more Methods, etc... If you separate each logic into services your AppComponent will be a hub of logic instead of a Blob Class – Manuel Panizzo Jun 17 '20 at 13:48