在Aurelia获取当前路线

Jef*_*f G 16 aurelia aurelia-router

要在非视图模型类中获取当前路由,最佳做法是注入路由器并使用this.router.history.fragment?或者这是不是吗?

Fab*_*Luz 26

您可以注入路由器并获取当前指令.像这样:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`currentInstruction`在构造函数中仍然是`null`,所以如果你想用它来绑定,你可以在`created`方法中得到它(另见[component lifecycle](http:// aurelia). IO/hub.html#/ DOC /条/奥里利亚/框架/最新/创建组件/ 3) (5认同)