我得到以下代码行的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
}
}
}
我究竟做错了什么??
2 回答
使用
否则
this
将不会指向当前的类实例。另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
您也可以 arrow-function 方式执行此操作:
箭头功能使“this”更具可预测性。
如果不需要 arg 则格式化: