Angular 2 — Detecting Router Changes

It’s important to know when an app begins and ends navigation transitions. For example, this is a useful technique for building loading indicators or showing users navigation errors. I had to dig around a bit to find the best solution for doing this with the new Angular Router.

The best way to achieve this is to hook into the ‘events’ property on the router instance. This is an observable that gets triggered when the state (or route) changes. The real magic happens in the callback that is fired when the route changes. The change event itself can be accessed as a parameter in the callback after subscribing to the observable.

The change event will be an extension of the router’s Event class. We are able to determine the context of the event by using the instanceof operator and checking if it is an instance of NavigationStart, NavigationEnd or NavigationError. (There are further events that I’m ignoring for the purpose of this example).

Once this structure is in place you can then hook into the route change flow. In the above example I have 3 tasks that fire for 3 specific route change events:

  1. If navigation starts, the app’s loading indicator should be shown.
  2. If navigation ends (successfully), the app’s loading indicator should hidden.
  3. If navigation errors, the app’s loading indicator should be hidden and the error should be presented to the user.

The third check is important as a fallback. If the navigation does not end successfully the loading indicator will remain shown; potentially locking the user out of the interface.

In an error scenario this catches the error. It presents it to the user whilst clearing active loading indicators, meaning they’re free to navigate elsewhere in the app. The error can be accessed from the error property on the change event.