在父母中知道选择了什么子路段?

时间:2016-05-25 07:08:53

标签: angular angular2-routing

我希望能够在父组件或应用程序组件中找到哪个子路由处于活动状态。例如,能够设置活动路径链接的样式。我看到[routeLink]添加了'router-link-active'类,但在我的例子中,我有一个'home',路由'/',无论我使用什么路由,它总是有这个类。有没有办法在出口的父母那里看到你的路线?

我从Location注入了@angular/common,并且当路线发生变化时我能够看到我想到的完整路径:

ngOnInit() {
  this.router.changes.subscribe(changes => {
    console.log('location info:', this.location.platformStrategy.path());
  });
}

有没有办法从父母那里获取RouteTree或当前有效的RouteSegment?或者检查router-outlet并查看加载到哪个组件?

2 个答案:

答案 0 :(得分:2)

您可以访问当前路线,例如

  constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
    router.changes.first().subscribe(() => {

      console.log('router', this.router);
      let urlTree = this.routeSerializer.parse(location.path());

      // to get the individual segments of the route use
      console.log('serializer', urlTree.children(urlTree.root)[0].segment);
      console.log('serializer', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
    });
  }

答案 1 :(得分:0)

在@Gunter的答案之后,这就是我最终的结果:

constructor(
  public router: Router,
  public routerSerializer: RouterUrlSerializer,
  public location: Location
) { }

ngOnInit() {
  this.router.changes.subscribe(changes => {
    this.updatePath();
  });
}

updatePath() {
  let path = this.location.path();
  let urlTree = this.routerSerializer.parse(path);
  let node = urlTree;
  let segment: UrlSegment = urlTree.root;
  let result = segment.segment;
  while (urlTree.children(segment).length > 0) {
    segment = urlTree.children(segment)[0];
    if (result.length > 1) result += '/';
    result += segment.segment; // is a string
  }

  this.path = result;
}

children()获取UrlSegment并返回UrlSegment数组。根segment.segment是一个空字符串,如果我想做到这一点,我可以这样做' /':

this.path = result.length == 0 ? "/" : result;