2016-12-13 166 views
1

V2.2.1,路由器 V3.2.1订阅儿童路线变化,知道父母在选择儿童路线段?

我和孩子有一个嵌套的路由器,路由器链路看起来是这样的:

/todo/iwgv4ehyav544f7c/zone1zone1todo/:id孩子航线)

/todo/iwgv4ehyav544f7c/zone2zone2todo/:id孩子航线)

现在请记住,todo/:id页面有它自己的路由器插座,可以显示孩子。

在父母(todo/:id)我有2个按钮,Button1和Button2。

我想在儿童路线zone1处于活动状态时显示Button1,并且在zone2处于活动状态时显示Button2。

我已成功地使东西,但我不认为这是正确的做法:

router.events 
    .filter(event => event instanceof NavigationEnd) 
    .map(value => value.url.split("/")) // what I get: ["","todo","iwgv4ehyav544f7c","zone1"] 
    .map(value => value[3]) // selecting the value at id 3 which is the child param 
    .subscribe(response => { 
     this.activatedChildUrl = response; // end value is "zone1" 
    }) 

是否有另一种更好的方式来订阅到路由器,得到孩子PARAMS,所以我可以使用这个值在父级?

编辑:

其他的事情到目前为止,我已经试过这并不能阻止维克托Savkin书工作:

activatedRoute.url.subscribe(() =>{ 
    activatedRoute.snapshot.firstChild.url[0].path 

}); // is firing only once 

回答

2

路由器有一个更加简单和优雅的解决方案,以确定哪条路径活动,您可以根据活动路线隐藏和显示元素。

文档https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#isActive-anchor

应用到我的项目上面的例子:

在TS:constructor(router: Router){}

在HTML:*ngIf="router.isActive('/todo/' + id + '/zone1')"

您从您的路线params中,从提取的ID您选择的对象。