8

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

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

4

1 回答 1

4

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

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

于 2019-02-02T11:19:41.883 回答