【问题标题】:Get child routes data in parent component获取父组件中的子路由数据
【发布时间】:2018-11-14 02:26:00
【问题描述】:

在我的 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

标签: angular routing angular2-routing


【解决方案1】:

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

【讨论】:

  • 不错。但是,即使在我离开父组件后,事件也会继续触发 - 我是否需要在离开后取消订阅才能结束事件?
  • @Sam 是的,您必须在 ngOnDestroy() 生命周期挂钩内取消订阅。
  • @Sam 如果解决了,您介意标记答案吗?谢谢
  • 当然,我只是想在标记答案之前让退订部分正常工作。
猜你喜欢
  • 1970-01-01
  • 2019-07-06
  • 2017-05-24
  • 2018-02-04
  • 2018-01-11
  • 2019-10-21
  • 1970-01-01
  • 2016-08-28
  • 2018-06-12
相关资源
最近更新 更多