angular - 将某个位置的“title”变量用于更高的模板
问题描述
我有一个适用于我的应用程序的模板(到目前为止)。有一个侧边栏、一个页眉和一个页脚,它们每个都在自己的组件中,所有的构建块都已就位。
问题是,我想使用与正在使用的视图相关的某些信息——例如,查询模块有一个 enquiry-new 组件,我想在标题组件中显示“新查询”作为标题。
我开始使用一项服务,但我不确定如何更新它,因为我尝试过但错误地使用了ngOnInit
(调用一次,因此标题上没有刷新/跟踪)。
我试图通过data
变量将任意数据传递到路由中。我发现的问题是ActivatedRoute
's data
observable 为父母提供数据,而不是孩子。我可以使用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'
}
}
];
//(...)
解决方案
推荐阅读
- url - 如何在 net/http 上返回 json
- spring - 当我还必须为 MVC 进程返回网页时,如何使用 Spring Rest MVC 返回响应正文?
- apache-spark - 无法实例化提供程序 org.apache.spark.sql.hive.orc.DefaultSource
- c# - 循环遍历数组,将值相互绑定
- python - 检查文本文件并使用正则表达式查找字符串模式
- elasticsearch - Elasticsearch 查询结果返回错误结果
- pointers - C语言数组和指针
- angular2-nativescript - 禁用 ListView 中的项目
- matlab - 在 Sfunction (ssGetT) 中获取 Sim 时间?
- typescript - 有人能解释一下'[P in keyof O]: O[P];' 方法?