Search code examples
aurelia

Access router object from child component(constroller/viewmodel) in Aurelia


I am new to Aurelia (but old in Angular), and trying to implement the routing configuration in my first app. I have configured the route in app.js like this:

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

and the helper function is written in a seperate file:

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
      },
    ]);
  }
}

Now in access module I can access the router object and in its html I can do navigation and print navigation model.

In child components (other pages) using html directives works fine but the router object is not accessible from their js files. For example in 'app/account/signin/index.js' I want to use this function:

this.router.navigateToRoute('profile');

but router is not defined on this.


Solution

  • I have figured out. The router object is shared using aurelia's DI. So in any component I had to import the Router first:

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

    then injecting it in the component:

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

    and finally using it any where in the component:

    this.router.navigateToRoute('profile');
    

    hope this answer help others too. TG.