我正在使用router.event.subscribe
@angular/router
来观看url更改以执行if
语句,尽管event.subscribe
可以正常工作。但是我的问题是如何避免仅在这些URL上显示标题而重复if
语句。可能是router.subscribe
以外的其他内容,但不确定该使用什么。
基本上想要一个基于您所使用的URL的动态标题。
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);
}
});
}
}
假设您已在路线的data属性内分配了页面标题,如下所示:
{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}
关于angular - 使用router.subscribe的angular2观看URL更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38613960/