Angular 2 v3路由器 - 如何在子路由中获取父路由参数

时间:2016-07-21 16:57:20

标签: angular angular2-routing

我的路由定义为/ abc /:id / xyz

其中abc /:id解析为ComponentA,而/ xyz是路由器插座(ComponentB)中显示的子组件

导航到/ abc /:id / xyz时,当我在ComponentA中执行this.route.params.subscribe(...)(其中route是ActivatedRoute)时,我会看到:id。在ComponentB中做同样的事情我没有看到:id。我猜是ActivatedRoute正在使用网址段。

无论如何都要获得路线中的所有参数?

3 个答案:

答案 0 :(得分:11)

未经测试,但根据Savkin's blog,将以下内容放入子项中以获取父组件的路由器参数:

constructor(activatedRoute: ActivatedRoute, router: Router) {
    const parentActivatedRoute = router.routerState.parent(activatedRoute);
    this.id = parentActivatedRoute.params.map(routeParams => routeParams.id);
}

将该代码与Router guide中的代码进行比较,您需要在模板中使用带有id的AsyncPipe,或者您可以使用subscribe() ...或者您可以使用snapshot如果你确定id值不会改变:

this.id = parentActivatedRoute.snapshot.params['id'];

@Chris在下面的评论中提到:this.router.routerState.pathFromRoot(this.route)将返回一系列激活的路由,直到当前路线。 然后,您可以获取所有激活路线的参数。

更新RouterState.pathFromRoot(someRoute)标记为deprecated in master。在RC.5中,使用ActivatedRoute.pathFromRoot()

答案 1 :(得分:10)

To follow up on Mark's answer this seems to be the method that works in the final version of Angular 2:

constructor(route: ActivatedRoute) {
  let id = route.pathFromRoot[route.pathFromRoot.length - 1].snapshot.params["id"];
}

Update: Direct access to parent route snapshot from here:

constructor(route: ActivatedRoute) {
  let id = route.snapshot.parent.params['id'];
}

See also Angular 2: getting RouteParams from parent component for other options.

答案 2 :(得分:0)

父路由参数默认不传递给子,但您可以从子组件内的父路由访问它们。 @Mark Rajcok向你指出great post。我已在下面的帖子中概述了相关部分

   @Component({
      selector: 'team',
      template: `
        Team Id: {{id | async}}
        <router-outlet></router-outlet>
      `
    })
    class TeamCmp {
      id:Observable<string>;
      constructor(r: ActivatedRoute) {
        this.id = r.params.map(r => r.id);
      }
    }

    @Component({
      selector: 'details',
      template: `
        Details for Team Id: {{teamId | async}}
      `
    })
    class DetailsCmp {
      teamId:Observable<string>;
      constructor(r: ActivatedRoute, router: Router) {
//get parent activated route. 
        const teamActivatedRoute = router.routerState.parent(r);
        this.teamId = teamActivatedRoute.params.map(r => r.id);
      }
    }