我为以下代码行获得TypeError: Cannot set property 'error' of undefined
:this.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
}
}
}

我做错了什么?
答案 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 ( )