Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from router component to children components in Aurelia?

Lets say we have a component in Aurelia named UserRouter, which is a child router and handles routing to UserProfile, UserImages and UserFriends.

I want the UserRouter to load in the user from the API (on canActivate) and then pass this this user data to sub components.

Loading in the data is fine, how do I pass it down to sub components so they can all read it? e.g. placing an attribute on <router-view>.

I've tried the bindingContext argument on the bind() method of sub components but this hasn't worked.

Thanks

like image 321
Mike Avatar asked May 25 '15 21:05

Mike


3 Answers

The way I did this, was by adding additional information to the child router definition eg:

configureRouter(config, router){
   config.map([
  { route: [''], name: 'empty', moduleId: './empty', nav: false, msg:"choose application from the left" },
  { route: 'ApplicationDetail/:id',  name: 'applicationDetail',   moduleId: './applicationDetail', nav: false, getPickLists : () => { return this.getPickLists()}, notifyHandler : ()=>{return this.updateHandler()} }
]);

in the first route from this example, I pass in a text message by adding my own porperty 'msg' to the route object. in the second route I pass in some event handlers, but could have been some custom objects or antything else.

In the childmodel I receive these additional elements in the activate() method:

export class empty{
  message;

  activate(params, routeconfig){
    this.message=routeconfig.msg || "";
  }
}

I guess in your case, you would add the user object to the child router definition.

like image 64
Jurgen De Jonghe Avatar answered Oct 24 '22 19:10

Jurgen De Jonghe


You could bind the router/user object to the <router-view>

<router-view router.bind="router"></router-view>

I have the same issue, so I'd love to see what you come up with!!

like image 25
Moose Avatar answered Oct 24 '22 20:10

Moose


You could use the event aggregator to publish out an event with the data and the sub components could subscribe and listen for that event. This would avoid coupling between them. However, there may be a downside I'm not thinking of.

like image 21
AlignedDev Avatar answered Oct 24 '22 20:10

AlignedDev