首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >反应性表单异步验证器没有清除FormGroup中的错误。

反应性表单异步验证器没有清除FormGroup中的错误。
EN

Stack Overflow用户
提问于 2020-11-02 18:14:20
回答 1查看 1.2K关注 0票数 0

我正在使用一个简单的表单执行一个web应用程序,在values 10中接收两个值,我将在后端验证它们,执行一个HTTP调用。为此,我创建了一个运行完美的异步验证器。

问题:--当HTTP成功时,没有完全清除FormGroup中的错误。换句话说,FormGroup总是无效的。

errors对象的FormGroup中,有两个奇怪的东西我不知道,那就是isScalar和订阅。也许这就是问题所在?

我所呈现的行为:

  1. HTTP调用失败:错误设置正确,状态无效。
  2. HTTP调用成功:错误未被完全清除,状态无效。糟糕!!

FormGroup

代码语言:javascript
运行
复制
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],
});

异步验证器

代码语言:javascript
运行
复制
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成为有效。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-02 18:44:08

例如,我的电子邮件实时存在检查器。给你的拐杖。

代码语言:javascript
运行
复制
// 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

代码语言:javascript
运行
复制
export declare interface AsyncValidatorFn {
    (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}

Update:一位提问的同事没有注意到他在map中使用了of(null)of(null)需要swtichMap,而纯null需要映射。详细信息可以在答案下面的评论中找到。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64651024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档