可以吗?
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.'
答案 0 :(得分:0)
是的,但是您需要将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
}
};
}
}