11

In my viewmodel class, how do I get a reference to the current Router?

What I really want to do is get the current ModuleId.

In Durandal, there was system.getModuleId, but there is no system in Durandal, so I figure the router is going to have that information.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233

2 Answers2

3

The way to get a reference to the current router:

import {inject} from 'aurelia-framework'
import {router} from 'aurelia-router'

@inject(router)
constructor(router)
{
    this.router = router; //Do something with router.
}

Note: Do not inject "AppRouter" It's a different router. If you add a route to AppRouter, it will not work. It will work if you import Router.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • I think you need to import {Router} from 'aurelia-router' (uppercase) and @inject(Router) (also uppercase). See https://discourse.aurelia.io/t/how-to-use-navigatetoroute/2581/6 – Will Moore May 25 '19 at 05:34
2

One way (not sure, the optimal one) to access current moduleId is in activate hook of your class:

activate(params, routeConfig) {
    console.log(routeConfig.moduleId);
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • is `activate` on all classes? if so, could you possibly decorate it? (this might be a different question altogether – Callum Linington Jul 17 '15 at 13:55
  • yes, there is `activate` hook available for every viewmodel class. not sure about decoration it. it is also possible to inject router into viewmodel and check its `currentInstrustion.config.modelId`, but it's not nice. – dfsq Jul 17 '15 at 15:24
  • this will only return config for current route, not router. @Greg Gum answer is the correct one. – vidriduch May 31 '17 at 11:30
  • `activate` is not available in every view model. only on modules that are loaded via the router or by `compose`. "regular` components don't have `activate` – avrahamcool Apr 22 '18 at 10:51