我想在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
}
];
答案 0 :(得分:15)
如果您的路线在数据属性中使用您的路径名配置,如下所示:
{
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"}
,则应在控制台中打印componentZip
。