const appRoutes: Routes = [
  { path: 'parent', component: parentComp, data: { foo: 'parent data' }, children: [
    { path: 'child1', component: childComp1, data: { bar: 'child data 1' },
    { path: 'child2', component: childComp2, data: { bar: 'child data 2' }
  ]}
];

如果我导航到/parent/child2,然后查看parentComp中的ActivatedRoute,则定义了data.foo,但没有定义data.bar.我可以访问所有子元素的数组,但我不知道哪个子元素被激活了.

如何从父路由的组件访问激活的子路由的数据?

推荐答案

第一个子元素将允许您访问数据

constructor(route: ActivatedRoute) {
  route.url.subscribe(() => {
    console.log(route.snapshot.firstChild.data);
   });
}

Angular相关问答推荐

如何在Angular模块中的forRoot中注入配置

无法执行客户端功能Angular 17与ssr'

如何在Angular 17中使用Angular—calendum?

将Angular 17中的http服务与独立组件一起使用

首期日历发行

按Angular 从组件的 bootstrap 选项卡中删除活动类

要素存储更改根存储状态

确保我的角库S服务构建提供独立的友好提供功能

Ngrx Select 器返回部分对象

是否可以在Angular(12+)中迭代指定的范围而不是整个数组

在指令中获取宿主组件的templateRef

以 Angular 形式添加动态控件失败

PrimeNG:如何以编程方式更改分页器中的选定页面?

刷新页面导致 401 错误-Angular 8

angular 13 ng 构建库失败(ivy部分编译模式)

Angular2 测试 - 按 ID 获取元素

Angular 5 中 value 和 ngValue 的区别

Lint 错误:实现生命周期挂钩接口

缺少带有Angular的语言环境XXX的语言环境数据

Angular 应用程序必须在新部署后清除缓存