Angular,获取父路由组件

Angular, get parent route component

我正在构建一个 Angular 7 应用程序。 在这个应用程序中,我得到了嵌套路线。我希望能够检测到父路由正在使用的组件。我找到了一种在本地执行此操作的方法,但这不适用于生产(输出不同)。

我用的是这个方法:

   checkIfChild() {
    this.sub = this.route.parent.params.subscribe(params => {
      if (params['id']) {
        this.parentId = params['id'];
        if (this.route.parent.component['name'] === 'ProjectShowComponent') {
          this.parentType = 'Project';
        } else if (this.route.parent.component['name'] === 'CompanyShowComponent') {
          this.parentType = 'Company';
        } else if (this.route.parent.component['name'] === 'ContactShowComponent') {
          this.parentType = 'User';
        }
      }
    });
  }

方法 this.route.parent.component['name'] 在本地输出名称,但在生产环境中只输出字母 T。

我收到的是这条消息

TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context.

检测哪个父路由激活了子路由以便我可以对其进行操作的正确方法是什么?

就我个人而言,我会放弃与组件实例的直接耦合,而是使用路由的 data 属性,考虑到:

  • 您没有以任何方式与组件实例交互。
  • 您将组件实例类型映射到静态值。

假设路由定义如下:

const routes: Routes = [
  {
    path: 'production',
    component: ProductionParent,
    data: {parentRoute :'Production'},
    children: [{path: '', component: Child}] 
  },
  {
    path: 'system',
    component: SystemParent,
    data: {parentRoute :'System'},
    children: [{path: '', component: Child}] 
  }
];

@Component({})
export class ProductionParent{}

@Component({})
export class SystemParent{}

@Component({})
export class Child implements OnInit, OnDestroy {
  private parentSub = Subscription.EMPTY;
  parentRoute :string;


  constructor(private readonly route: ActivatedRoute){}

  ngOnInit(){
    this.trackParent();
  }

  ngOnDestroy(){
   this.parentSub.unsubscribe();
  }

  private trackParent(){
    this.parentSub = this.route.parent
                        .data
                        .subscribe(data => this.parentRoute = data.parentRoute || 'unknown');
  }
}

这很可能可以通过其他方式实现,但这是我想到的第一个实用方法。希望对你有帮助。