【发布时间】:2020-07-27 20:15:23
【问题描述】:
我正在尝试为我的 Angular 10 应用程序实现标题服务。我需要订阅路由事件,抓取激活路由的组件,看看它是否实现了title() getter,然后用它来设置页面的标题。听起来很简单……
代码:
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.rootRoute(this.route)),
filter((route: ActivatedRoute) => route.outlet === "primary"),
filter(
(route: ActivatedRoute) =>
ComponentWithTitleBase.isPrototypeOf(route.component as any)
),
map((route) => (route.component as unknown) as ComponentWithTitleBase),
tap(console.dir)
)
.subscribe((comp: ComponentWithTitleBase) => {
this.titleSvc.title = comp.title;
});
但comp.title 始终未定义。即使组件确实实现了get title() getter:
export class AboutComponent extends ComponentWithTitleBase implements OnInit {
get title(): string {
return "About the demo";
}
...
}
我看到 console.dir 输出 AboutComponent。我在这里错过了什么?
【问题讨论】:
-
您可以使用
<router-outlet (activate)="updateTitle(componentInstance)"event 来获取当前的组件实例 stackoverflow.com/questions/40294262/… -
我不能,因为我有多个 - 一个在另一个里面,等等。我不想去把(激活)所有这些。
-
你不需要全部都去激活,你可以创建一个指令
标签: angular typescript angular-routing