角度,获取父路线组件

时间:2019-02-02 11:03:40

标签: angular angular-routing angular-activatedroute

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

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

1 个答案:

答案 0 :(得分:2)

就个人而言,考虑到以下几点,我将直接耦合到组件实例,而使用路由的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');
  }
}

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

相关问题