首页 > 解决方案 > 角度嵌套路由父到子变量

问题描述

我有这条路线:

{ 
  path: ':parent_id',
  component: Parent, 
  children: [
    {
      path: 'child',
      children: [
        {
          path: ':child_id',
          component: Child
         }
      ]
    }
  ]
}

如何从子组件中检索 parent_id 值?

标签: angular

解决方案


您应该可以使用ActivatedRoute

首先导入它:import {ActivatedRoute} from "@angular/router";

然后尝试这样的事情:

constructor(private route: ActivatedRoute) {

  this.route.parent.params.subscribe((params) => {
    console.log(params); // This would show you all the available params

    if (params['parent_id']) { 
      console.log(params['term']) // Prints the console parent_id param
    }
  });

}

推荐阅读