在 parent 组件中获取 child 路由数据

Get child routes data in parent component

在我的 angular 模块路由中,我有一个 parent 组件包含 child 个组件作为 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>

在 parent 组件中 TeacherTabcontrolComponent 我需要从路由访问数据 {title: ...}。我在 .ts 代码中尝试了以下内容:

constructor(
    private _route: ActivatedRoute,
) {
    this._route.url.subscribe((e) => {
        console.log(e, this._route.snapshot.firstChild.data);
    });
}

这很好用,但仅在第一次进入 parent 组件时有效。当我从一个 child 切换到另一个时,没有触发任何事件。

如何在从一个 child 导航到另一个时收到通知?

您可以在父组件中订阅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);
    }
);