Angular2 : get parent router data

2020-02-14 06:08发布

问题:

I'm creating a component under route /blabla/:id/blabla/:secondid

First part of my url "/blabla/:id/..." is managed by my first routing component.

Then, a second router manages the second part of url.

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

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

Any idea ?

回答1:

Pass the first id along with data-binding.



回答2:

You must use Injector to get parents data.

This is a sample code extrated from here using the feature.

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

Take a look at the constructor and how the injector is used to get the great parent's userLogin

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's 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)
      );
  }

}