【问题标题】:Angular, get parent route componentAngular,获取父路由组件
【发布时间】:2019-02-02 11:03:40
【问题描述】:

我正在构建一个 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.

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

【问题讨论】:

    标签: angular angular-routing angular-activatedroute


    【解决方案1】:

    就个人而言,我会放弃与组件实例的直接耦合,而是使用路由的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');
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 2016-12-19
      • 2017-11-20
      • 2019-07-06
      • 2018-11-14
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      相关资源
      最近更新 更多