typescript Angular 2获取父激活路由

zzwlnbp8  于 2022-11-30  发布在  TypeScript
关注(0)|答案(3)|浏览(129)

我有一条路径,其中包含如下路径子项:

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

bqjvbblv

bqjvbblv1#

您可以通过使用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

ckx4rj1h

ckx4rj1h2#

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

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
    );
  }
olhwl3o2

olhwl3o23#

有一种非常稳定的、有Angular 的方法可以做到这一点:

import {ActivatedRoute, Router, UrlTree} from '@angular/router';

 //...

 constructor(private router: Router, private route: ActivatedRoute) {}

 doSomethingWithParentRoute() {
     
     // you can create a UrlTree for the parent path by:
     const prantUrlTree: UrlTree = this.router.createUrlTree(['../'], { relativeTo: this._route });
     // of course you can go higher if you want by using sg like '../../../'

     // Then you can use the urlTree as you wish:
     let path: string = this.router.serializeUrl(urlTree);
     // or
     path = this.urlTree.toString();
     // etc...

     // additionally you can also access your parent route as an ActivatedRoute object by:
     const parentRoute: ActivatedRoute = this.route.parent;
 }

**注意:**如果您使用〈Angular 11,或者您在路由器模块中设置了relativeLinkResolution: 'legacy',则'../'引用路径中的同一级别,因此您可能需要使用'../../'。https://angular.io/guide/deprecations#relativeLinkResolution

相关问题