我正在使用一个简单的表单执行一个web应用程序,在values 10中接收两个值,我将在后端验证它们,执行一个HTTP调用。为此,我创建了一个运行完美的异步验证器。
问题:--当HTTP成功时,没有完全清除FormGroup中的错误。换句话说,FormGroup总是无效的。
在errors
对象的FormGroup中,有两个奇怪的东西我不知道,那就是isScalar和订阅。也许这就是问题所在?
我所呈现的行为:
FormGroup
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仍然是无效的。
我的目标是在FormGroup调用成功时正确清除FormGroup的错误,使FormGroup成为有效。
发布于 2020-11-02 18:44:08
例如,我的电子邮件实时存在检查器。给你的拐杖。
// In component
this.form = new FormGroup({
// ...
email: new FormController(
'email',
[...],
[ValidatorsHelper.isEmailExistValidator(this.http)]
),
// ...
};
// Async validator
class ValidatorsHelper {
// ...
static isEmailExistValidator(http: HttpClient): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
return http.post<boolean>(AUTH_REG_EMAIL, { data: control.value }).pipe(
map((result) => result ? null : { exist: true }),
catchError(() => {
return of({ exist: true });
}),
);
};
}
// ...
}
本质:return (formGroup: FormGroup):
-> return (control: AbstractControl):
在form.d.ts
中
export declare interface AsyncValidatorFn {
(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
Update:一位提问的同事没有注意到他在map
中使用了of(null)
。of(null)
需要swtichMap,而纯null需要映射。详细信息可以在答案下面的评论中找到。
https://stackoverflow.com/questions/64651024
复制相似问题