首页 > 代码库 > [Angular] Subscribing to router events

[Angular] Subscribing to router events

In our root component, one thing we can do is subscribe to Router events, and do something related to router events. So how can we get router event?

 

export class AppComponent implements OnInit {  constructor(private router: Router) {}  ngOnInit() {    this.router.events      .subscribe(events => console.log(events))  }}

To events we log out from ‘this.router.events‘ is actually the same as we enable router tracing.

 

If you only interested in one event ‘NavigationEnd‘, we can use RxJS filter:

import rxjs/add/opreator/fitler;export class AppComponent implements OnInit {  constructor(private router: Router) {}  ngOnInit() {    this.router.events      .filter(event => event instanceof NavigationEnd)      .subscribe(events => console.log(events))  }}

 

Here we use ‘instanceof‘, this is because which event is a class. So we can use instanceof to filter according to the class.

 

[Angular] Subscribing to router events