首页 > 解决方案 > 将某个位置的“title”变量用于更高的模板

问题描述

我有一个适用于我的应用程序的模板(到目前为止)。有一个侧边栏、一个页眉和一个页脚,它们每个都在自己的组件中,所有的构建块都已就位。

问题是,我想使用与正在使用的视图相关的某些信息——例如,查询模块有一个 enquiry-new 组件,我想在标题组件中显示“新查询”作为标题。

我开始使用一项服务,但我不确定如何更新它,因为我尝试过但错误地使用了ngOnInit(调用一次,因此标题上没有刷新/跟踪)。

我试图通过data变量将任意数据传递到路由中。我发现的问题是ActivatedRoute's dataobservable 为父母提供数据,而不是孩子。我可以使用firstChild,但是当路线更改时标题不会刷新。

我正在查看有关使用Input方法的文档,但是由于模板正在使用router-outlet它似乎不起作用(我无法让 Angular 喜欢它,而且我仍然不知道如何正确刷新它)。

有没有合适的方法来做到这一点?我有什么明智的做法吗?也许我从一个不好的角度集中注意力,但我不知道如何以简单的方式做到这一点。


我觉得发布代码会令人困惑,但也许它为我想要什么/我尝试了什么提供了一些想法。也许下面的代码完全是垃圾,我走错了路。也许可以挽救。请注意,使用服务或使用路线的数据是不同的(排他性的?)方法,我都被这两种方法困住了。

// header.component.ts

@Component({
(...)
export class HeaderComponent implements OnInit {
  ngOnInit() {
    // Conceptually, using Tried using a service here
    this.title = this.extraRouteInfoService.getTitle();
    // alternatively, something along
    this.title = this.route.data.pipe(map(data => data.title));
    // or with some conceptual method that doesn't exist
    this.title = this.route.getDataForLastChildCurrentRoute(magic);
  }
}
<!-- header.component.html -->
<div>
...
<h1>{{ title | async }}</h1>
...
</div>
<!-- home.component.html -->
<div>
<app-layout-header></app-layout-header>
  <main class="content">
    <router-outlet></router-outlet>
  </main>
</div>
// home-routing.module.ts
const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    canActivate: [AuthGuard],
    data: {
      title: 'Home',
    },
    children: [
      {
        path: 'enquiries',
        loadChildren: '../enquiries/enquiries.module#EnquiriesModule'
      }
    ]
  }
];
//(...)
// enquiries-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: EnquiryListComponent,
    data: {
      title: 'All enquiries'
    }
  },
  {
    path: 'new',
    component: EnquiryNewComponent,
    data: {
      title: 'New enquiry'
    }
  }
];
//(...)

标签: angular

解决方案


推荐阅读