typescript Angular 2 获取父激活路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42483570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:17:43  来源:igfitidea点击:

Angular 2 get parent activated route

angulartypescriptangular-routerangular-activatedroute

提问by peppermcknight

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 /dashboardbut possible with Angular 2 and not in JavaScript, but also I can accept JavaScript code too but primary Angular 2.

如何/dashboard使用 Angular 2 而不是 JavaScript,但我也可以接受 JavaScript 代码,但主要是 Angular 2。

回答by peppermcknight

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

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

}

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

您可以在此处更详细地查看 ActivatedRoute 中的所有内容:https: //angular.io/api/router/ActivatedRoute

回答by Eugen Sunic

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