这是允许的吗?
export class H{
passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
...
validatePassword(control: FormControl) {
...
return (REG_EXP.test(password)) ? null : {
validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
valid: false,
message: this.passwordErrorMessage //can I do this?
}
};
}
}对于我的一个测试用例,我得到以下错误
TypeError: Cannot read property 'passwordErrorMessage' of undefined
Error object: Property name: ngDebugContext, value: [object Object]
Error object: Property name: ngErrorLogger, value: function () { [native code] }
TypeError: Cannot read property 'passwordErrorMessage' of undefined
at HelperService.validatePassword (webpack:///./src/app/helper.service.ts?:224:31)看起来this就是undefined。我仍然处于调试的早期阶段,但我的第一个疑问是this的用法是否正确?如果我将用法更改为message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.',则一切正常
发布于 2020-10-14 01:55:53
可以,但您需要将validatePassword绑定到类,或者使用箭头函数将this上下文传递给该函数。这应该是可行的:
export class H{
passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
...
validatePassword = (control: FormControl) => {
...
return (REG_EXP.test(password)) ? null : {
validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
valid: false,
message: this.passwordErrorMessage
}
};
}
}https://stackoverflow.com/questions/64340596
复制相似问题