Angular 是否未调用FormGroup asyncValidator?
我已经研究这个问题很长时间了,我发现了一些问题,但是没有一个能帮助我解决这个问题。这是最接近实际的问题。我试图为formGroup调用asyncValidator,但无法使其工作。任何帮助都将不胜感激 在下面的代码中,http请求甚至没有被激发 这是我的Angular 是否未调用FormGroup asyncValidator?,angular,angular-validation,Angular,Angular Validation,我已经研究这个问题很长时间了,我发现了一些问题,但是没有一个能帮助我解决这个问题。这是最接近实际的问题。我试图为formGroup调用asyncValidator,但无法使其工作。任何帮助都将不胜感激 在下面的代码中,http请求甚至没有被激发 这是我的表单组 const partners = this.formBuilder.array([]); this.patientRestrationForm = this.formBuilder.group( {
表单组
const partners = this.formBuilder.array([]);
this.patientRestrationForm = this.formBuilder.group(
{
patientFileId: new FormControl(null),
firstName: new FormControl(null, Validators.required),
secondName: new FormControl(null, Validators.required),
lastName: new FormControl(null, Validators.required),
aliasName: new FormControl(null),
patientDob: new FormControl(null, Validators.required),
patientEmail: new FormControl(null, [Validators.email, Validators.required]),
socialSecurityNo: new FormControl(null),
passportNo: new FormControl(null),
countryCodeId: new FormControl(null),
patientMobileNo: new FormControl(null),
partners: partners,
},
{
asyncValidator: (control: AbstractControl) => {
return this.asyncValidator.bind(control)
}
});
这是asyncValidator
asyncValidator(control: AbstractControl): Promise<any> | Observable<any> {
const patientFileId = control.get('patientFileId');
const countryCodeId = control.get('countryCodeId');
const patientMobileNo = control.get('patientMobileNo');
const patientEmail = control.get('patientEmail');
if (patientEmail.value) {
return this.asyncValidationService.validateEmailNotTaken(patientEmail, patientFileId)
}
}
asyncValidator(control:AbstractControl):承诺验证程序必须链接到字段,而您的asyncValidator
未链接到表单中的字段,这就是它从未被调用的原因(请参阅)
您的异步验证逻辑依赖于多字段,我认为您应该在submit event上设置此逻辑,以便确保设置了所有属性(如果您使用Validators.required
将它们设置为required),并且如果整个表单有效,您将能够向kno发出请求(因为此验证器不链接到单个字段)
解决方案是删除此asyncValidator
,并将其逻辑放入submit方法中,如果请求未验证表单内容,则将错误标志设置为true
旁注:返回此.asyncValidator.bind(控件)
无法工作,绑定到控件将导致此成为控件,其中asyncValidationService
未定义。您不应该在此处使用绑定。您可以添加将表单链接到模板的部分吗?@Supamiu,我更新了PostThank,但根据文档,异步fn应该如何运行,formGroups
就像formControls
const form=new FormGroup({password:new FormControl(“”)passwordConfirm:new FormControl(“”)},{validators:passwordMatchValidator,asyncValidators:otherValidator})是的,但正如您所看到的,formControl只绑定到一个输入,您的验证器在表单中获取多个值,这不是控件的使用方式。此外,您将验证器和异步验证器绑定到两个不同的对象中,这不是使用验证器的文档化方式。我现在重新测试了,异步函数仅在如果整个表单是有效的,因为如果输入无效,表单将不会提交,这就是为什么您的验证不能像您期望的那样工作。
public validateEmailNotTaken(a: AbstractControl, b?): Observable<{ [key: string]: any }> {
console.log('called::', a.value);
return this.httpService.getRequest(
'PatientsRegistration/IsPatientEmailExist' + '?control=' + a.value + '&id=' + b.value,
).map((response: HttpResponse<boolean>) => {
return !response.body ? null : { asyncInvalid: true };
});
}
<form [formGroup]="patientRestrationForm" autocomplete="off" autocomplete="nope"
(ngSubmit)="onSubmit()">