Unknown to some is the Aurelia router supports events. Using the Event Aggregator dependency in Aurelia, we can actually listen to various events fired via the router. All events can be subscribed to using the Event Aggregator dependency and the subscribe method.
It is worth noting that you don’t always need to use the Event Aggregator, sometimes a router pipeline step is all that is needed to hook into a certain aspect of the router flow and in some cases, this might be the desired choice.
The events the Aurelia router fires are as follows:
- router:navigation:processing
- router:navigation:error
- router:navigation:canceled
- router:navigation:success
- router:navigation:complete
Rather than digging through the documentation yourself, here you go. But you’re probably wondering, at what stage do any or all of these get called within the lifecycle of the router? Good question.
router:navigation:processing
This event appears to be fired for anything that relates to the router doing something. Looking in the unit test which has some insights, we can see that when the router successfully navigates, is cancelled or errors out, that this event is always fired. Basically this event is saying, “every time you see this fired, the router is processing a route instruction”
router:navigation:error
A pretty obvious event. When there is an error, this event gets fired.
router:navigation:canceled
Another fairly obvious event. When a routing action is cancelled, such as inside of a custom pipeline step which checks if the user is logged in, this event gets fired.
router:navigation:success
Once a routing action has been completed, such as a user click a button and being navigated to a particular page and there are no errors, this event fires.
router:navigation:complete
Once everything is complete (not necessarily successful) this event fires. From what I can decipher, the complete event is similar to that of the processing event. The processing event is the first even to always fire before anything else and the complete event is the last event to fire. This event will always fire regardless of if there was an error or success within the routing process.
Using the Event Aggregator with Router events
If you are after a guide on how you can use the Event Aggregator, look no further than this post which describes how to subscribe to events.