Blog

I'm looking for:

Router Events in Angular

 

When working with Angular Routing, it’s very useful to be able to respond to routing events – the most obvious and useful being when the route changes. In AngularJS this was accomplished with by attaching a callback function to one the “$routeChange” events on the $scope. In Angular the concept is similar but has some key (and in my opinion, useful) differences.

Once you have a reference to the Router for your application you can subscribe to its “events” observable. This observable will emit a route-event whenever applicable that you can listen for. Being an observable you can subscribe to it in multiple places, filter for the specific event you want, transform the raw event, or anything else you could do with an observable.

 constructor(private router: Router) { router.events //.filter((evt) => evt instanceof NavigationStart || evt instanceof NavigationEnd) .subscribe((evt) => { console.log(evt); if (evt instanceof NavigationStart) { console.log("Route Change Start!"); } else if (evt instanceof NavigationEnd) { console.log("Route Change End!"); } }); } 

In the above code snippet, I’m just subscribing to the events observable of the router and then outputting the actual event to the console. There’s a commented-out filter statement to prevent the observable from firing for any event except the ones I’m actually interested in, and in the subscribe callback I’m outputting a message to the console based on the type of router event that was fired.

You can see this in action with this plunker.

Now you can react to a router event (most likely a route change start and route change end) and perform some action. For example, I commonly use this to display an overlay with a spinning progress icon over the entire app while the route finishes resolving, then hide the overlay once complete.

You can view Angular’s documentation about route events here.



Looking for a new job? We work with some of the biggest names in tech, and we’re hiring! Check out our open jobs and make your next career move with Planet.