我在用着router.event.subscribe
@angular/router
观察 url 变化以执行if
虽然声明event.subscribe
工作正常。但我的问题是我怎样才能避免重复我的if
声明只是为了在这些网址上显示标题。这可能是别的东西router.subscribe
但不确定为此使用什么。
基本上想要一个基于您所在网址的动态标题。
this._router.events.subscribe((event) => {
console.log('route changed');
if(this.location.path() == '/1'){
this.title = 'Title 1';
} else if(this.location.path() == '/2'){
this.title = 'Title 2';
}
});
我不知道这是否有意义。我可以更改我的route.ts路径以具有类似的内容{ path: 'Title-1' }
然后删除-
通过做.replace()
但这样做会给我 www.mysite.com/Title-1 但它看起来不太友好。
这是我的方法,效果很好,特别是对于嵌套路由:
我使用递归辅助方法在路线更改后获取最深的可用标题:
@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);
}
});
}
}
假设您已在路线的数据属性中分配页面标题,如下所示:
{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)