首页 文章

TypeError 无法设置 undefined 的属性

提问于
浏览
-1

我得到以下代码行的TypeError: Cannot set property 'error' of undefinedthis.error = error.code;

这是我正在尝试做的事情(它是一个 Angular Reactive Form,调用一个 Web 服务):

@Component({
  // ...
})
export class SignUpComponent implements OnInit {
  // More declarations...
  error: string | null; // I also tried error = '' and error = null
  // Constructor, etc.

  public submit() {

    this.error = null;
    if (this.signUpForm.valid) {
      // Create an Auth0 user
      this.authService.signUp(this.signUp.value.email, this.signUp.value.password, this.authServiceCallback);
    }
  }

  public authServiceCallback(error) {
    if (error) {
      // This will cause an error child component to appear
      this.error = error.code;
    } else {
      // Do something else
    }
  }
}

我究竟做错了什么??

2 回答

  • 7

    使用

    this.authService.signUp(this.signUp.value.email, this.signUp.value.password, 
          this.authServiceCallback.bind(this));
    

    否则this将不会指向当前的类实例。

    另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  • 3

    您也可以 arrow-function 方式执行此操作:

    this.authService.signUp(this.signUp.value.email, this.signUp.value.password, x => this.authServiceCallback ( x (or whatever) ) );
    

    箭头功能使“this”更具可预测性。

    如果不需要 arg 则格式化:

    () => this.authServiceCallback ( )
    

相关问题