Angular2: get parent router data

I am creating a component under route / blabla /: id / blabla /: secondid

The first part of my url "/ blabla /: id / ..." is controlled by my first routing component.

Then the second router manages the second part of the URL.

In my component, I can easily access my ": secondid" in RouteData.

But I wonder how I can access my "id" from there.

Any idea?

+4
angular angular2-routing
Feb 09 '16 at 18:15
source share
2 answers

Pass the first id along with the data binding.

+3
Feb 09 '16 at 23:27
source share

You must use Injector to obtain parent data.

This is an example of code that has been crossed out from here using this function.

  this.params = injector.parent.parent.get(RouteParams); this.userLogin = this.params.get('userLogin'); 

Take a look at the constructor and how Injector used to get the great userLogin parent

 import {Component, Injector} from 'angular2/core'; import {Http} from 'angular2/http'; import {ROUTER_DIRECTIVES, Router, RouteParams, RouteConfig} from 'angular2/router'; @Component({ directives: [ROUTER_DIRECTIVES], template: ` <div class="col-sm-3"> <img class="img-circle" src="" /> <p *ngIf="userData.name"> <i class="glyphicon glyphicon-user"></i> </p> <p *ngIf="userData.company"> <i class="glyphicon glyphicon-briefcase"></i> </p> <p *ngIf="userData.location"> <i class="glyphicon glyphicon-globe"></i> </p> </div> <div class="col-sm-9"> </div> `, styles: [` img { width: 100px; margin-bottom: 10px; } `] }) export class UserDetail { params: RouteParams; userLogin: string; userData: Object = {}; constructor(public http: Http, params: RouteParams, injector: Injector, private _router: Router) { // We use injector to get a hold of the parent params this.params = injector.parent.parent.get(RouteParams); this.userLogin = this.params.get('userLogin'); } ngOnInit() { this.http.get(`http://api.github.com/users/${this.userLogin}`) .map(response => response.json()) .subscribe( data => this.userData = data, err => console.log(err) ); } } 
+2
Mar 01 '16 at 22:44
source share



All Articles