从Aurelia的子组件(constroller / viewmodel)访问路由器对象

时间:2018-12-01 04:59:16

标签: aurelia aurelia-router

我是Aurelia的新手(但在Angular中是老手),并尝试在我的第一个应用程序中实现路由配置。我已经在app.js中配置了路由,如下所示:

configureRouter(config, router) {
    RoutingHelper.exerciseOneRouteConfig(this, config, router);
  }

和helper函数写在一个单独的文件中:

routing_helper.js

import {
  PLATFORM
} from 'aurelia-pal';

export class RoutingHelper {
  static exerciseOneRouteConfig(self, config, router) {
    self.router = router;
    config.title = 'تمرین ۱';
    config.map([{
        route: ['', 'home'],
        name: 'home',
        moduleId: PLATFORM.moduleName('app/index'),
        title: 'خانه',
        nav: true
      },
      {
        route: ['account'],
        name: 'account',
        moduleId: PLATFORM.moduleName('app/account/index'),
        title: 'حساب کاربری',
        nav: true
      },
      {
        route: ['profile'],
        name: 'profile',
        moduleId: PLATFORM.moduleName('app/account/profile/index'),
        title: 'پروفایل کاربر',
        nav: false
      },
      {
        route: ['signup'],
        name: 'signup',
        moduleId: PLATFORM.moduleName('app/account/signup/index'),
        title: 'ثبت نام',
        nav: false
      },
      {
        route: ['signin'],
        name: 'signin',
        moduleId: PLATFORM.moduleName('app/account/signin/index'),
        title: 'ورود کاربر',
        nav: false
      },
      {
        route: ['changepass'],
        name: 'changepass',
        moduleId: PLATFORM.moduleName('app/account/signin/changepass'),
        title: 'تغییر کلمه عبور',
        nav: false
      },
    ]);
  }
}

现在在访问模块中,我可以访问路由器对象,并且在其html中,我可以进行导航和打印导航模型。

在子组件(其他页面)中使用html指令可以正常工作,但是无法从其js文件访问router对象。例如在“ app / account / signin / index.js”中,我要使用此功能:

this.router.navigateToRoute('profile');

但是在此未定义路由器。

1 个答案:

答案 0 :(得分:1)

我知道了。路由器对象使用aurelia的DI共享。因此,在任何组件中,我都必须先导入Router

...
import {
  Router
} from 'aurelia-router';
...

然后将其注入组件中

...
@inject(Router)
...
constructor(router){
  this.router = router;
}
...

并最终在组件中的任何位置使用它:

this.router.navigateToRoute('profile');

希望这个答案也能帮助其他人。 TG。

相关问题