0

我想将多个组件(Component1 | Component2)传递到我的 canDeactivate 防护中,所以我使用下面这样的泛型。

问题- 我想从我传入的每个组件中访问一个属性,那么如何获取通用组件属性?

我必须投还是什么?我可以在调试器中看到该组件在那里,但是直到我在函数内部才能访问属性。

仅供参考 -component.profileForm.dirty不起作用,因为在我进入函数之前它不知道 T 是什么

export class PreventUnsavedChangesGuard <T> implements CanDeactivate <T> {

  constructor(private confirmService: ConfirmService) {}

  canDeactivate(component: T): Observable < boolean > | boolean {
    if (component.hasOwnProperty('profileForm')) {
      if (component.profileForm.dirty) {
        return this.confirmService.confirm();
      }
    }
    return true;
  }

}

4

1 回答 1

1

您可以定义一个接口,其中包含您希望组件拥有的最少信息,例如,

interface HasProfileForm {
    profileForm: Form
}

然后您可以修改您的警卫以使用新界面,例如,

export class PreventUnsavedChangesGuard <T extends HasProfileForm> implements CanDeactivate <T> {

  constructor(private confirmService: ConfirmService) {}

  canDeactivate(component: T): Observable<boolean> | boolean {
    if (component.hasOwnProperty('profileForm')) {
      if (component.profileForm.dirty) {
        return this.confirmService.confirm();
      }
    }
    return true;
  }
}
于 2020-11-22T08:01:45.290 回答