Angular 2获得父激活路由

问题描述 投票:4回答:2

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

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

angular typescript angular-router angular-activatedroute
2个回答
11
投票

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

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


1
投票

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

 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
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.