Angular中Header组件显示当前路由标题始终返回undefined问题求助
问题原因
你直接注入的ActivatedRoute是Header组件对应的路由节点,但Header组件一般位于路由出口之外(比如根组件模板中),它关联的是根路由,而根路由通常没有配置title。浏览器标题能正常更新是因为Angular会自动遍历整个激活路由树,找到最底层路由配置的title并同步到浏览器,但你的代码只拿到了根路由的title,自然是空值。
解决方案
方案一:遍历激活路由树获取title
通过Router监听路由导航完成事件,从根路由开始遍历所有子路由,找到带有title的激活路由节点:
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'; import { filter, map, switchMap } from 'rxjs/operators'; export class HeaderComponent implements OnInit { public title$; constructor(private router: Router, private activatedRoute: ActivatedRoute) {} ngOnInit() { this.title$ = this.router.events.pipe( // 仅监听导航完成事件 filter(event => event instanceof NavigationEnd), map(() => { let currentRoute = this.activatedRoute.root; // 遍历至最底层的激活路由 while (currentRoute.firstChild) { currentRoute = currentRoute.firstChild; } return currentRoute.title; }), // 订阅title的Observable获取实际值 switchMap(titleObs => titleObs) ); } }
组件HTML保持不变:
<header> <h1>My Website - {{ title$ | async }}</h1> </header>
方案二:复用Title服务的结果
既然浏览器标题已经能正常更新,说明Angular的Title服务已经拿到了正确的title值,直接订阅这个服务的结果即可:
import { Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { map } from 'rxjs/operators'; export class HeaderComponent { public title$; constructor(private titleService: Title) { // 若浏览器标题格式为"My Website - 页面标题",可移除前缀 this.title$ = this.titleService.getTitle().pipe( map(fullTitle => fullTitle.replace('My Website - ', '')) ); // 若浏览器标题就是纯页面标题,直接使用: // this.title$ = this.titleService.getTitle(); } }
内容的提问来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

