簡體   English   中英

Angular 2 獲取父激活路由

[英]Angular 2 get parent activated route

我有一條路線,路線孩子是這樣的:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM