更新时间:2023-08-25 14:24:01
这是我的方法,特别适用于嵌套路由:
Here's my approach which works fine, especially for nested routes:
路线更改后,我使用递归帮助器方法来获取最深的可用标题:
I use a recursive helper method to grab the deepest available title after a route has changed:
@Component({
selector: 'app',
template: `
<h1>{{title}}</h1>
<router-outlet></router-outlet>
`
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
title: string;
private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
if (routeSnapshot.firstChild) {
title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
}
return title;
}
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.title = this.getDeepestTitle(this.router.routerState.snapshot.root);
}
});
}
}
这是假设您已经在路线的data属性内分配了页面标题,如下所示:
This is assuming, that you have assigned page titles within the data property of your routes, like this:
{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}