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

标签 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
    }
];

最佳答案

如果您的路由在数据属性中配置了您的路由名称,如下所示:

{
    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/

相关文章:

angularjs - 更改 $scope.$on 函数中的 $scope.variable 不会更新 View

javascript - 是否可以在用户离开时删除整个网页?

javascript - 如何设置和锁定CKEditor窗口大小?

javascript - 从弹出 jsp 中检索值到 javascript

angular - 命名 socket 中的延迟加载模块抛出错误

javascript - 在 ui-sref 中过滤

javascript - for 循环中的回调完成后如何执行函数?

Angular ngx-translate 内部服务

angular - 在订阅中捕获错误是不可能的吗?

javascript - Angular UI-Router $urlRouterProvider 。当我单击 <a ui-sref ="..."> 时不工作时