我正在实现一个 AsyncValidatorFn。
服务:
public verifyExistingRegisterScheduled(workschedule: WorkSchedule): Observable<Result<any>> {
return this.dataService.post<Result<any>>('/workschedule/existing-register-scheduled', workschedule);
}
组件:
createForm() {
this.scheduleForm = this.formBuilder.group({
searchText: [this.searchText],
codEnd: [this.workschedule.codEnd, Validators.required],
dataInicio: [this.workschedule.dataInicio, Validators.required],
dataFim: [this.workschedule.dataFim, Validators.required],
periodo: [this.workschedule.periodo, Validators.required],
justificativa: [this.workschedule.justificativa, Validators.required],
totalColaboradores: [this.workschedule.totalColaboradores],
totalTerceiros: [this.workschedule.totalTerceiros]
},
{
validator: [dateLessThanValidator, existingRegisterScheduledValidator(this.workScheduleService, this.workschedule)]
});
}
验证器:
export function existingRegisterScheduledValidator(workScheduleService: WorkscheduleService, workschedule: WorkSchedule): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
return workScheduleService.verifyExistingRegisterScheduled(workschedule).pipe(map(result => {
debugger;
return (result.content && result.content.length > 0) ? { 'registerExists': true } : null;
}));
}
};
HTML
<div *ngIf="scheduleForm.errors && scheduleForm.errors['registerExists']" class="alert alert-danger col-sm-12">Message.</div>
这个想法是,如果返回值,则错误可能是真的。
不工作。我做错了什么?
最佳答案
您错误配置了asyncValidator
。请参阅docs供使用
createForm() {
this.scheduleForm = this.formBuilder.group({
searchText: [this.searchText],
codEnd: [this.workschedule.codEnd, Validators.required],
dataInicio: [this.workschedule.dataInicio, Validators.required],
dataFim: [this.workschedule.dataFim, Validators.required],
periodo: [this.workschedule.periodo, Validators.required],
justificativa: [this.workschedule.justificativa, Validators.required],
totalColaboradores: [this.workschedule.totalColaboradores],
totalTerceiros: [this.workschedule.totalTerceiros]
},
{
validators: [dateLessThanValidator],
asyncValidators :[existingRegisterScheduledValidator(this.workScheduleService, this.workschedule)]
});
关于javascript - 如何显示来自 AsyncValidatorFn 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57793481/