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

3 ответа

Решение

Вы можете сделать это, используя родительское свойство на 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

Вы можете проверить родительский маршрут, определив, присутствует ли в нем только один слеш:

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

Существует довольно стабильный, Angularish способ сделать это:

       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.

Другие вопросы по тегам