【发布时间】:2021-02-15 10:23:50
【问题描述】:
我正在使用一个简单的表单在 Angular 10 中做一个 Web 应用程序来接收两个值,我将在后端验证它们,执行 HTTP 调用。为此,我创建了一个运行完美的异步验证器。
问题: HTTP 调用成功时,FormGroup 中的错误并没有完全清除。换句话说,FormGroup 总是无效的。
在FormGroup 的errors 对象内部,有两个我不知道的奇怪的东西,isScalar 和subscribe。也许这就是问题所在?
我正在展示的行为:
- HTTP 调用失败:错误设置正确,状态为无效。一切顺利。
- HTTP 调用成功:错误未完全清除,状态为无效。糟糕!
表单组
this.form = this.fb.group({
// I will validate this two values with the backend
patientIdentifications: this.fb.group({
clinicRecord: [null, Validators.required],
documentId: [null, Validators.required]
}, {
updateOn: 'blur',
asyncValidators: CustomValidators.isPatientValid(this.myService) // <= async validator
}),
// Just to illustrate that I have more FormControls
firstName: [null, Validators.required],
});
异步验证器
export class CustomValidators {
static isPatientValid(myService: MyService): AsyncValidatorFn {
return (formGroup: FormGroup):
Promise<ValidationErrors | null> |
Observable<ValidationErrors | null> => {
const clinicRecordControl = formGroup.controls.clinicRecord;
const documentIdControl = formGroup.controls.documentId;
const clinicRecordValue = clinicRecordControl.value;
const documentIdValue = documentIdControl.value;
return myService.getPatient(clinicRecordValue, documentIdValue).pipe(
// Returning "null" if there is a response to clear the FormGroup's errors.
map(patient => patient ? of(null) : of({valid: true})),
catchError(() => of({valid: true}))
);
};
}
}
当两个输入失去焦点时,HTTP 调用完美完成。但即使 HTTP 调用成功,FormGroup 仍保持为 INVALID。
我的目标是在 HTTP 调用成功时正确清除 FormGroup 的错误,以使 FormGroup 为 VALID。
【问题讨论】:
标签: angular angular-reactive-forms