Router events
Learn about how to subscribe to and handle router events.
Last updated
Was this helpful?
Revision created
refactor(event): no longer call prevent default by default (#1926) BREAKING CHANGE: no longer calling preventDefault on all events, this can be switched back to v1 behavior via IListenerBindingOptions [skip ci] * BREAKING CHANGE: no longer reexport fetch plugin from aurelia package * fix(router-lite): dont register config * chore: cleanup unused methods, correct typings on test fixture
Learn about how to subscribe to and handle router events.
Last updated
Was this helpful?
You can use the lifecycle hooks ( and ) to intercept different stages of the navigation when you are working with the routed components directly. However, if you want to tap into different navigation phases from a non-routed component, such as standalone service or a simple custom element, then you need to leverage router events. This section discusses that.
The router emits the following events.
au:router:location-change
: Emitted when the browser location is changed via the and events.
au:router:navigation-start
: Emitted by router before executing a routing instruction; or in other words, before performing navigation.
au:router:navigation-end
: Emitted when the navigation is completed successfully.
au:router:navigation-cancel
: Emitted when the navigation is cancelled via a non-true
return value from canLoad
or canUnload
lifecycle hooks.
au:router:navigation-error
: Emitted when the navigation is erred.
The events can be subscribed to using the . However, there is another type-safe alternative to that.
To this end, inject the IRouterEvents
and use the IRouterEvents#subscribe
.
Note that the event-data for every event has a different type. When you are using TypeScript, using IRouterEvents
correctly types the event-data to the corresponding event type and naturally provides you with intellisense. This type information won't be available if you subscribe to the events using the event aggregator.
The following example demonstrates the usage of router events, where the root component displays a spinner at the start of navigation, and removes it when the navigation ends.
This is shown in action below.