gpt4 book ai didi

angular2 使用 router.subscribe 来观察 url 的变化

转载 作者:太空狗 更新时间:2023-10-29 17:26:45 26 4
gpt4 key购买 nike

我正在使用 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'
}
}

关于angular2 使用 router.subscribe 来观察 url 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38613960/

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