【问题标题】:Access router object from child component(constroller/viewmodel) in Aurelia从 Aurelia 中的子组件(控制器/视图模型)访问路由器对象
【发布时间】:2018-12-12 07:21:47
【问题描述】:

我是 Aurelia 的新手(但在 Angular 中很老),并试图在我的第一个应用程序中实现路由配置。我在 app.js 中配置了这样的路由:

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

并且辅助函数写在一个单独的文件中:

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 文件访问路由器对象。例如在 'app/account/signin/index.js' 我想使用这个功能:

this.router.navigateToRoute('profile');

但路由器并没有在此定义。

【问题讨论】:

    标签: aurelia


    【解决方案1】:

    我想通了。路由器对象使用 aurelia 的 DI 共享。所以在任何组件中我都必须先导入Router

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

    然后将其注入到组件中:

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

    最后在组件的任何地方使用它:

    this.router.navigateToRoute('profile');
    

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

    【讨论】:

    • 这是我的建议:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2018-01-04
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多