简体   繁体   中英

Angular 2 get parent activated route

I have a route with route children like this:

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

And in the browser I want to get the activated parent route like

host.com/dashboard/wage-types

How to get the /dashboard but possible with Angular 2 and not in JavaScript, but also I can accept JavaScript code too but primary Angular 2.

You can do this by using the parent property on the ActivatedRoute - something like this.

export class MyComponent implement OnInit {

    constructor(private activatedRoute: ActivatedRoute) {}

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

}

You can see everything from the ActivatedRoute in more detail here: https://angular.io/api/router/ActivatedRoute

You can check for parent route by determining if only one slash is present in it:

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

There is a pretty stable, Angularish way to do so:

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

NOTE: If you use < Angular 11, or you have relativeLinkResolution: 'legacy' set in your router module, then the '../' refers to the same level in the path, so you probably want to use '../../' . Read more: https://angular.io/guide/deprecations#relativeLinkResolution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM