Angular Router Event Name

天大地大妈咪最大 提交于 2021-01-27 21:13:11

问题


The Angular(2+) router has an events property that is a rxjs subject.

Once subscribed, you are able to listen for events like:

router.events.subscribe((event: Event) => { console.log(event) });

but the problem is you have no way to obtain the event type since it listens for all events. A hacky solution is you can inspect the constructor name of the event like:

router.events.subscribe((event: Event) => {
  if(event.constructor.name === 'NavigationStart') {
    loadingService.start();
  } else if(event.constructor.name === 'NavigationEnd') {
    loadingService.complete();
    drawerService.destroyAll();
  }
});

I was curious if there was a better way to accomplish this?


回答1:


Event is only the base class.

The concrete event values are one of

  • NavigationStart
  • NavigationEnd
  • NavigationCancel
  • NavigationError
  • RoutesRecognized

You can for example use:

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:NavigationStart) => {
      // You only receive NavigationStart events
    });

See also How to detect a route change in Angular 2?




回答2:


If you install @bespunky/angular-zen you could extend RouteAware and create an event handler method named onNavigationEnd like so:

import { Component                                        } from '@angular/core';
import { NavigationStart, NavigationEnd, RoutesRecognized } from '@angular/router';
import { RouteAware                                       } from '@bespunky/angular-zen/router-x';

@Component({
    selector   : 'app-demo',
    templateUrl: './demo.component.html',
    styleUrls  : ['./demo.component.css']
})
export class DemoComponent extends RouteAware
{
    // ✨ Any router event can have a handler method.
    // See https://angular.io/guide/router#router-events for a complete list of angular's router events.

    // ✨ Use `this.router` to access the router
    // ✨ Use `this.route` to access the activated route
    // ✨ Use `this.componentBus` to access the RouterOutletComponentBus service
    
    protected onNavigationStart(event: NavigationStart): void
    {
        console.log(`Navigation started for: ${event.url}`);
    }

    protected onRoutesRecognized(event: RoutesRecognized): void
    {
        console.log('Recognized routes.');
    }
    
    protected onNavigationEnd(event: NavigationEnd): void
    {
        console.log(`Navigation ended for: ${event.url}`);
    }
}

Here's a live example

The library is open source and you can install it like this:

npm install @bespunky/angular-zen



来源:https://stackoverflow.com/questions/42786927/angular-router-event-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!