2016-08-15 14 views
11

最新のバージョン@angular/router3.0.0-rc.1 URL /ルートからパラメータを取得する方法が変更されました。Angular 2 new Router:子コンポーネントのルータパラメータを取得する方法は?

thisドキュメントに基づいて、paramsを購読することでそのパラメータを取得できるはずですが、私の場合は動作していないようです。

私が達成したいのは、paramsを親コンポーネントの子ルートから取得することです。

たとえばのは、これが私のルートであるとしましょう:

const routes: Routes = [ 
    { 
    path: 'parent', 
    component: ParentComponent, 
    pathMatch: 'prefix', 
    children: [ 
     { 
     path: ':id', 
     component: ChildComponent 
     } 
    ] 
    } 
]; 

私はidパラメータを取得し、私のparentComponentでそれを使用したいです。 だから私はこのようにしようとしている。このよう

export class ParentComponent implements OnInit { 

    sub: any; 
    constructor(
    private route: ActivatedRoute) { 
    this.route = route; 
    } 

    ngOnInit() { 

    this.sub = this.route.params.subscribe(params => { 
    let id = params['id']; 
    console.log(id); 
    }); 

    } 

} 

私は取得しています:

未定義

を、私はここで何をしないのですか?

答えて

17

ActivatedRouteには、親子ルート情報にアクセスするゲッターがあります。

親からの最初の子のルートにアクセスするためには、使用します。

this.route.firstChild.params

あなたがchildrenプロパティを使用するすべての子のルートを望んでいた場合。あなたが親から子ルートと必要なパラメータにあった場合、これはActivatedRoute

this.route.children

の配列を返します。

this.route.parent.params

+0

ありがとう@Brandon! –

5

パラメータが関連付けられている子/子供ActivatedRouteで保存します。彼らは親のActivatedRouteでは利用できません。そのため、まずgetter firstChildまたはchildrenを使って子供のActivatedRouteを取得する必要があります。

その後、親は子のパラメータの変更を購読することができ、次のいずれか

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { ActivatedRoute }    from '@angular/router'; 
import { Subscription }     from 'rxjs/Subscription'; 

export class ParentComponent implements OnInit, OnDestroy { 
    private sub: Subscription; 
    constructor(private route: ActivatedRoute) {} 
    ngOnInit() { 
     this.sub = this.route.firstChild.params.subscribe(
     params => console.log(params.id)); 
    } 
    ngOnDestroy() { 
     this.sub.unsubscribe(); 
    } 
} 

か、子パラメータのスナップショットを取得することができます:あなたはすべてを取得したい場合は

import { Component }  from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 

export class ParentComponent { 
    constructor(private route: ActivatedRoute) {} 
    someMethod() { 
     console.log(this.route.firstChild.snapshot.params.id); 
    } 
} 

を(複数のアウトレットがある場合など)、ActivatedRoute.childrenまたはActivatedRouteSnapshot.childrenを使用して、子ActivatedRoutesまたは子ActivatedRouteShapshotsの配列を取得します。

+1

ちょっと@マーク、有益な答えをありがとうが、私たちは常にパラメータの定期購読を解除する必要がありますか? –

0

this.activatedRoute.snapshot.firstChild.params

関連する問題