How To Get The Current Active Route In An Aurelia ViewModel

Last updated: February 21, 2016

When inside of an Aurelia ViewModel there are situations where you might want to know what the current route is within a ViewModel.

One such scenario I encountered recently where I had one View and ViewModel pair being accessed by 5 different routes. I needed to know what route was accessing my ViewModel to load different data.

This is what the second parameter of the activate method for.

activate(params, navigationInstruction) {
    console.log(navigationInstruction);
}

The navigationInstruction parameter gives you the information about the route currently accessing the ViewModel. This allows you to access everything about the route, including the navModel

This object has a tonne of information about the currently active route accessing this ViewModel:

  • moduleId – The current module path to the ViewModel (defined in app.js/app.ts)
  • name – The name of your route (defined in app.js/app.ts)
  • navModel – This pretty much gives you the same values as the other properties with exception of a couple, like isActive and relativeHref
  • route – The route pattern (defined in app.js/app.ts)
  • settings – The settings object defined in the route (defined in app.js/app.ts)
  • title – The title value for this route
  • viewPorts – An object of defined viewports for this route (defined in app.js/app.ts)

In my scenario, I needed to know the name of the route accessing the ViewModel. I knew if it was my route for numeric pagination, I could check for specific parameters. If it was the route with no parameters, I knew not to check for them and just fetch all data.

Hopefully this helps you in determining the current route in Aurelia and what is accessing your ViewModel.

 

Dwayne

 

3 thoughts on “How To Get The Current Active Route In An Aurelia ViewModel

  1. Thanks for the tip!

    Although `routeConfig.navModel.href` gets me the active url, this only seems to work when the application is already loaded and I’m actually navigating from one url to another, i.e. not when I reload the application. In that case, the navModel is still empty (at least in Aurelia v1).

    Any thoughts?

  2. I find that on the initial load, there is only one argument passed to activate(), and it’s undefined. Any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *