【问题标题】:Angular 2 get parent activated routeAngular 2获取父激活路线
【发布时间】:2017-02-27 10:38:22
【问题描述】:

我有一条这样的路线子路线:

{
    path: 'dashboard',
    children: [{
        path: '',
        canActivate: [CanActivateAuthGuard],
        component: DashboardComponent
    }, {
        path: 'wage-types',
        component: WageTypesComponent
    }]
}

在浏览器中,我想获得激活的父路由,例如

host.com/dashboard/wage-types

如何获得/dashboard,但可以使用 Angular 2 而不是 JavaScript,但我也可以接受 JavaScript 代码,但主要是 Angular 2。

【问题讨论】:

  • 只有使用父组件才有可能。
  • @RomanC 你能给我看一些代码吗

标签: angular typescript angular-router angular-activatedroute


【解决方案1】:

您可以通过使用 ActivatedRoute 上的 parent 属性来执行此操作 - 类似这样。

export class MyComponent implement OnInit {

    constructor(private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.activatedRoute.parent.url.subscribe((urlPath) => {
            const url = urlPath[urlPath.length - 1].path;
        })
    }

}

您可以在此处更详细地查看 ActivatedRoute 中的所有内容: https://angular.io/api/router/ActivatedRoute

【讨论】:

  • 是的,但这给了我一个数组,我如何过滤以仅获取 /dashboard ?
  • 因为您使用的是当前激活路由的父级,所以 UrlSegments 数组中的最后一项将是父级 url - 更新了我的答案以显示这一点并反映我的错误 url 属性是实际上是一个可观察的
【解决方案2】:

您可以通过确定其中是否只有一个斜杠来检查父路由:

 constructor(private router: Router) {}

 ngOnInit() {
      this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((x: any) => {
          if (this.isParentComponentRoute(x.url)) {
            // logic if parent main/parent route
          }
        });
  }

 isParentComponentRoute(url: string): boolean {
    return (
      url
        .split('')
        .reduce((acc: number, curr: string) => (curr.indexOf('/') > -1 ? acc + 1 : acc), 0) === 1
    );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2017-07-21
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多