2017-01-09 55 views
9

我試着去獲得:在如何獲得:孩子航線的ID PARAM從父組件在Angular2

RouterModule.forRoot([ 
    { 
    path: 'orders', 
    component: ListComponent, 
    children: [ 
     { 
     path: 'view/:id', 
     component: ViewComponent 
     }, 
    ] 
    } 
]) 

從ListComponent定義ID PARAM。

我已經嘗試:

route: ActivatedRoute 

route.params.subscribe(params => { 
    let id = +params['id']; 
}) 

從ListComponent,但參數數組是空的,我想它,因爲:ID參數所屬到viewComponent不listComponent

我怎樣才能在ID PARAM listComponent?

回答

8

可以使用firstChild屬性或ActivatedRoute讓孩子航線:

route.firstChild.snapshot.params['id'] 
+0

看起來像屬性routerState不存在ActivatedRoute,我也想獲得父組件中的id不是子組件,所以我用route.firstChild.params –

+0

我誤解了這個問題,並假設@run碼回答你真正想要的東西。我更新了我的答案。 –

+0

完美,它的工作原理,謝謝 –

0

可以保留通過route.firstChild.params['id']挖如果僅僅是一個孩子的路線或使用類似route.children[0].children[1].params['id']挖通過使用括號符號的多個級別來訪問同級路線。當談到找到正確的水平時,它有點試驗和錯誤。

+0

謝謝我已經這樣做 –

3

獲取父組件內孩子的參數,可以我用ActivatedRoute的則firstChild屬性,因爲我只有孩子航線上

route: ActivatedRoute 

route.firstChild.params.subscribe(params => { 
    let id = +params['id']; 
}); 
+1

唯一正確的答案,因爲事情從來沒有發生在Angular同步,這個答案也包含訂閱(異步)部分。 –

+0

迄今爲止的最佳答案,它涵蓋了訂閱點。 –

1

遞歸發現孩子PARAMS不會總是得到你正在尋找的PARAMS 。特別是在移動路線時。

相反,RxJS ReplaySubject可用於發佈當前的子標識。

創建新的服務:

@Injectable() 
export class ChildIdService { 
    current$ = new ReplaySubject<number>(); 
} 

導入它的子組件上並訂閱重播主題:

export class ChildComponent implements OnInit { 
    constructor(private ar: ActivatedRoute, public ci: ChildIdService){} 

    ngOnInit(){ 
    this.ar.params.map(params => +params.id).subscribe(this.ci.current$); 
    } 
} 

導入父組件的服務,並使用異步管認購給孩子的價值:

<span>Mother component child ID: {{ci.current$ | async}}</span> 

這是一個工作片段:https://stackblitz.com/edit/angular-b8xome(添加/孩子/ 42瀏覽應用程序的預覽,看看它的工作)


或者定義下的組件和兄弟姐妹和家長componentless路線,例:https://vsavkin.com/the-powerful-url-matching-engine-of-angular-router-775dad593b03「同級組件使用相同的數據」

+0

使用ReplaySubject而不是其他類型主題的任何特定原因?我仍然試圖爲他們掌握用例,所以在這個例子中理解它會有所幫助。 – Seedmanc

+0

ReplaySubject會記住以前的結果,使得未來的訂閱成爲可觀察的熱點。 如果您在多個位置訂閱此可觀察項並希望訪問以前推送的結果,這會很有幫助。 – golfadas