Angular2 : get parent router data
Asked Answered
B

2

4

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 ?

Boorish answered 9/2, 2016 at 18:15 Comment(2)
simple use RouteParams to send id while routingKimbell
How can I do this ? In my second router, I can access to my routeParams in my constructor to know the value of the first :id. But how can I propagate this to my routes ?Boorish
R
3

Pass the first id along with data-binding.

Raber answered 9/2, 2016 at 23:27 Comment(2)
How can you bind data to your component while routing ? Second router looks like this @Component({...template: '<router-outlet></router-outlet>'...}) @RouteConfig([{path: '/blabla/:id', name: 'SecondRouting', component: FinalComponent}]) How can I bind any stuff to FinalComponent?Boorish
K I think I found my answer there : github.com/angular/angular/issues/4452Boorish
T
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)
      );
  }

}
Thomson answered 1/3, 2016 at 22:44 Comment(1)
This no longer seems to work as of Angular 2.0.0-beta.16 (2016-04-26)Penna

© 2022 - 2024 — McMap. All rights reserved.