To get the current route within a non-view-model class, would the best practice be to inject the Router and use this.router.history.fragment? Or is this a no-no?
Asked
Active
Viewed 8,562 times
1 Answers
28
You could inject the router and get the current instruction. Like this:
import { inject } from 'aurelia-dependency-injection'; //or framework
import { Router } from 'aurelia-router';
@inject(Router)
export class MyClass {
constructor(router) {
this.router = router;
}
getRoute() {
return this.router.currentInstruction.config.name; //name of the route
//return this.router.currentInstruction.config.moduleId; //moduleId of the route
}
}

Fabio
- 11,892
- 1
- 25
- 41
-
5Please note that `currentInstruction` is still `null` in the constructor, so if you want to use it for binding, you can get it in the `created` method (see also the [component lifecycle](http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/creating-components/3) – Erik Vullings Jan 02 '17 at 13:48
-
I am getting the data of the previous route here, any idea why??? Thanks. – IngoB Oct 09 '17 at 20:46
-
Probably because the view hasn't changed yet. Check if you have a `canDeactivate` function – Fabio Oct 10 '17 at 02:17
-
I cannot edit my own comment, but the [component lifecycle](http://aurelia.io/docs/fundamentals/components#the-component-lifecycle) link has changed. – Erik Vullings Nov 24 '17 at 22:52