angular - 获取父组件中的子路由数据
问题描述
在我的角度模块路由中,我有一个包含子组件作为 tabitems 的父组件。
路由:
{
path: "teacher/:id", component: TeacherTabcontrolComponent,
children: [
{ path: 'dialogue', component: TeacherTabpageDialoguesComponent, data: { title: 'Dialoge' } },
{ path: 'settlements', component: TeacherTabpageSettlementsComponent, data: { title: 'Settlements' } },
{ path: 'timesheets', component: TeacherTabpageTimesheetsComponent, data: { title: 'Timesheets' } },
{ path: 'transactions', component: TeacherTabpageTransactionsComponent, data: { title: 'Transactions' } },
]
},
中的选项卡式控件TeacherTabcontrolComponent
:
<ul class="nav nav-tabs">
<li routerLinkActive="active"><a [routerLink]="['dialogue']">Dialogue</a></li>
<li routerLinkActive="active"><a [routerLink]="['transactions']">Transactions</a></li>
<li routerLinkActive="active"><a [routerLink]="['settlements']">Settlements</a></li>
<li routerLinkActive="active"><a [routerLink]="['timesheets']">Timesheets</a></li>
</ul>
<div class="tab-content">
<router-outlet></router-outlet>
</div>
在父组件TeacherTabcontrolComponent
中,我需要从路由访问数据 {title: ...}。我在我的 .ts 代码中尝试了以下内容:
constructor(
private _route: ActivatedRoute,
) {
this._route.url.subscribe((e) => {
console.log(e, this._route.snapshot.firstChild.data);
});
}
这很好用,但仅在第一次进入父组件时。当我从一个孩子切换到另一个孩子时,不会触发任何事件。
从一个孩子导航到另一个孩子时如何收到通知?
解决方案
router.events
您可以在父组件中订阅。这样在每次路由更改时,您都可以获得路由的子数据。
constructor(private _route: ActivatedRoute, private _router: Router)
this._router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(
() => {
console.log(this._route.snapshot.firstChild.data);
}
);
推荐阅读
- html - 从primeng以角度实现日历时出错
- puppet - 测试木偶中未定义的事实
- python - 带有硒测试的 Django 频道 2 失败
- html - Bootstrap nav-justified 不占用全宽
- go - Windows 如何为 Golang 制作
- r - 比 r 中的 ifelse() 更快的函数
- intellij-idea - 在 IntelliJ 中启用自定义 CheckStyle
- php - array_merge():参数 #1 不是 laravel 5.5 中的数组
- javascript - 不能要求 npm 安装的模块
- sql - 从“with table as”CTE 表达式创建临时表