gpt4 book ai didi

Angular - 在路由器事件中获取组件实例

转载 作者:行者123 更新时间:2023-12-04 09:19:15 25 4
gpt4 key购买 nike

我正在尝试为我的 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() setter/getter :
export class AboutComponent extends ComponentWithTitleBase implements OnInit {
get title(): string {
return "About the demo";
}

...
}
我看到了 console.dir输出 关于组件 .我在这里缺少什么?

最佳答案

基于@yurzui 的想法,您可以为此使用指令:
激活的component.directive.ts

@Directive({
selector: 'router-outlet'
})
export class ActivatedComponentsDirective {

constructor(r: RouterOutlet, titleService: TitleService) {
r.activateEvents.pipe(
// takeUntil(r.destroyed),
).subscribe(compInstance => compInstance.title && titleService.newTitle(compInstance.title))
}

ngOnDestroy () {
// destroyed.next;
// destroyed.complete();
}
}
标题.service.ts
@Injectable({
providedIn: 'root'
})
export class TitleService {

private src = new Subject<string>();

newTitle (t: string) {
this.src.next(t);
}

constructor() { this.initConsumer() }

private initConsumer () {
this.src.pipe(
/* ... */
).subscribe(title => {
console.log('new title', title);
})
}
}
ng-run demo .

关于Angular - 在路由器事件中获取组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63122863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com