2016-08-15 105 views
11

@angular/router3.0.0-rc.1的最新版本中從URL /路由獲取參數的方式發生了變化。Angular 2 new Router:如何獲取子組件的路由器參數?

根據this文檔,您應該能夠通過訂閱參數來獲取參數,但在我的情況下似乎不起作用。

我想要實現的是將params引入父組件FROM子路由。

例如,讓我們說,這是我的路線:

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

我想要得到的id參數和我爲父級使用它。 所以我想是這樣的:

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 firstChildchildren來獲得孩子的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.childrenActivatedRouteSnapshot.children獲取一組兒童ActivatedRoutes或兒童ActivatedRouteShapshots。

+1

嗨@Mark,感謝您提供豐富的答案,但是我們是否總是需要取消訂閱參數訂閱? –

0

使用this.activatedRoute.snapshot.firstChild.params

相關問題