我想在 app.component.html
模板中显示路由名称。我正在寻找一个简单的解决方案,可以这样写:
{{router.currentRoute.name}}
我当前的路由器配置:
export const routes: RouterConfig = [
{
path: '',
redirectTo: '/catalog',
pathMatch: 'full'
},
{
path: 'catalog',
name: 'Catalog', // Is this property deprecated?
component: CatalogComponent
},
{
path: 'summary',
name: 'Summary',
component: SummaryComponent
}
];
最佳答案
如果您的路由在数据属性中配置了您的路由名称,如下所示:
{
path: 'somepath',
component: SomeComponent,
data: {
name: 'My Route Name'
}
}
在您的 app.component.ts
中,您可以 import 'rxjs/add/operator/filter';
+ import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
并执行以下操作:
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => {
let currentRoute = this.route.root;
while (currentRoute.children[0] !== undefined) {
currentRoute = currentRoute.children[0];
}
console.log(currentRoute.snapshot.data);
})
}
这将监听 NavigationEnd
事件,然后向下遍历到当前路线,以便您可以访问该路线的 data
。
如果您在 /somepage
上使用上面的代码,它应该在您的控制台中打印 { name="My Route Name"}
。
关于javascript - Angular 2,如何显示当前路由名称? (路由器 3.0.0-beta.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38763901/