Angular 2 get parent activated route

后端 未结 2 425
北海茫月
北海茫月 2020-12-18 00:40

I have a route with route children like this:

{
    path: \'dashboard\',
    children: [{
        path: \'\',
        canActivate: [CanActivateAuthGuard],
          


        
相关标签:
2条回答
  • 2020-12-18 00:58

    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

    0 讨论(0)
  • 2020-12-18 01:01

    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
        );
      }
    
    0 讨论(0)
提交回复
热议问题