我遇到了一个问题,我的私有(private)类变量在运行时未定义。代码是:
export class AdminRegistrationComponent {
adminRegistrationForm:ControlGroup;
usernameValidation:FormValidation;
constructor(private fb:FormBuilder) {
this.usernameValidation = new FormValidation(AdminRegistrationValidations.username);
this.adminRegistrationForm = fb.group({
username: new Control("", this.usernameValidation.valid)
});
}
submit() {
console.log(this.adminRegistrationForm);
}
}
和FormValidation
:
export class FormValidation {
constructor(private regex:RegExp) {
}
valid(control:Control):ValidationResult {
if (this.regex.test(control.value)) {
return null;
}
return {"valid”": true};
}
get():string {
return this.regex.toString().slice(1, -1);
}
}
问题是当在 this.usernameValidation 上调用 valid 时,FormValidation
中的私有(private)正则表达式变量在运行时未定义(我已确认正在传递正确的值)。我读过在 Angular2 中有一些需要考虑的依赖注入(inject)条件,但我什么都做不了。本质上,我已经尝试将这些类列为 @Injectable
,以及其他类似的东西。我得到的确切错误是:
异常:TypeError:无法读取未定义的属性“test”
谢谢
最终编辑
下面提到的答案是我的有效函数需要是箭头函数:
valid = (control:Control):ValidationResult => {
if (this.regex.test(control.value)) {
return null;
}
return {"valid”": true};
}
最佳答案
he private regex variable in FormValidation is undefined at run-time (I have confirmed the right value is being passed in).
很可能 regex
未定义:
constructor(private regex:RegExp) {
}
如果不是,则调用 valid(control:Control):ValidationResult {
时使用了错误的 this
。修复使用箭头:
valid = (control:Control):ValidationResult => {
if (this.regex.test(control.value)) {
return null;
}
return {"valid”": true};
}
关于箭头函数的更多信息:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
关于javascript - 为什么我的构造函数参数私有(private)类成员在运行时未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35764257/