2017-03-01 10 views
0

私のアプリケーションルートコンポーネントでは、コンテナ内にいくつかのスタイルを持つrouter-outletがあります。 ChildContainerで変数を取得するためにAngular2がapp-rootの子ルートからデータを取得しています

{ 
    path: 'some-path', 
    component: ChildContainer, 
    data: { variable:'variable' }, 
} 

そして、私がすることができますが、私はAPPROOTでそれを必要とする: は私がルートを持っています。だから、documentationから私はchildからそれを得ることができますが、私はAPPROOTコンストラクタでこれを行う場合:

const state: RouterState = router.routerState; 
const root: ActivatedRoute = state.root; 
const child = root.firstChild; 

console.log(root, child) - 子供がnullであり、根は(プロパティのゲッターを呼び出す)正しい子が含まれています。 AppRootでvariableを取得するにはどうすればよいですか?

答えて

3

インスタンスをアクティブにして、インスタンス化されたコンポーネントの参照をルータのアウトレット内に取得することができます。

はチェックここでこのSO question

@Component({ 
    selector: 'my-app', 
    template: `<h3 class="title">Basic Angular 2</h3> 
    <router-outlet (activate)="onActivate($event)" ></router-outlet> 
    ` 
}) 
export class AppComponent { 
    constructor(){} 

    onActivate(componentRef){ 
    componentRef.sayhello(); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `<h3 class="title">Dashboard</h3> 
    ` 
}) 
export class DashboardComponent { 
    constructor(){} 

    sayhello(){ 
    console.log('hello!!'); 
    } 
} 

Plunker!!

更新

パブリックプロパティとしてActivatedRouteを公開し、あなたがルーティングされたコンポーネントの参照を持っていたら、データをサブスクライブ

onActivate(componentRef){ 
    componentRef.route.data.subsribe(data => { 
     console.log(data); 
    }); 
} 

これがうまくいきますように!

+0

ありがとうございますが、少し違います。私の場合は、ルータデータから変数を取得する必要があります。https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html#!#data-anchor –

+0

@qweasd:あなたのコメント、乾杯! –

関連する問題