首页 文章

订阅子路线更改,在父母中了解选择了哪个子路线段?

提问于
浏览
1

Angular v2.2.1, Router 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"
     })

Is there another better way to subscribe to the router and get the child params, so I can use this value in the parent?

编辑:

到目前为止,我尝试过的其他一些东西在Victor Savkin的书中没有用到:

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

}); // is firing only once

1 回答

  • 2

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

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

    应用于我上面的项目示例:

    在TS中: constructor(router: Router){}

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

    您从路径参数或所选对象中提取ID .

相关问题