TypeError无法设置undefined的属性

时间:2017-05-15 11:37:44

标签: angular typescript

我为以下代码行获得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 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

您也可以采用箭头功能方式:

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

箭头功能使"这个"更可预测。

如果不需要arg则格式化:

() => this.authServiceCallback ( )