Angular 2,如何显示当前路由名称? (路由器3.0.0-beta.1)

时间:2016-08-04 09:44:18

标签: javascript angular angular-ui-router

我想在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
    }
];

1 个答案:

答案 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