2016-08-15 108 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

相关问题