首页 > 解决方案 > 无法读取未定义的属性“”

问题描述

我目前正在尝试在执行 loadModalDialog 后加载模式。我试图在 then 部分中调用它。我收到一个错误

Cannot read property 'dialog' of undefined

如果我以以下方式调用,我不会收到上述错误,但会收到与 userservice 中的依赖项相关的错误,因为 loadModalDialog 启动了对协议组件的调用,该组件查看来自 userService 执行的值。因此,我需要确保在执行 userService 之后需要调用 this.loadModalDialog()。我需要将 this.dialog 的实例传递给函数 loadModalDialog 吗?

  this.userService.load();
  this.loadModalDialog();

零件

constructor( public dialog: ModalDialogService ) {

    export class AppComponent implements OnDestroy {
      this.userService.load().then(this.loadModalDialog);
      }));
     }

    private loadModalDialog() {
    const ref = this.dialog.open(AgreementComponent, {
      // size: 'large'
    });
    ref.afterClosed.subscribe(result => {
      console.log('3rd dialog closed', result);
    });
  }

标签: angular

解决方案


您正在删除将this函数传递给.then语句时的上下文。

您的错误消息是一个危险信号,这this不是您认为this应该的。它应该和.bind(this)你的this.loadModalDialog函数一样简单。

this.userService.load().then(this.loadModalDialog.bind(this));

或者

this.userService.load().then(() => this.loadModalDialog());


推荐阅读