【问题标题】:Angular11 asyncvalidator custom validator error not added to reactive form errors listAngular11 asyncvalidator 自定义验证器错误未添加到反应式表单错误列表中
【发布时间】:2021-10-16 18:19:10
【问题描述】:

我有一个响应式表单并添加了一个自定义异步验证器,以通过检查可用值数组来检查输入的值是否唯一。正在调用验证器,但验证错误“重复”未添加到表单字段错误中,并且未显示在模板中。不知道我在这里做错了什么。

component.ts

private registerFormGroup(): void {
        this.titleField = new FormControl(
            { value: this.auditTemplate.title, disabled: true },
            [Validators.required],
            [TemplateNameValidator.createValidator(this.auditTemplateService)]
        );

        this.templateForm = this.formBuilder.group({
            title: this.titleField,
            tags: [this.auditTemplate.tags]
        });
    }   

名称验证器:

export class TemplateNameValidator {
    static createValidator(auditTemplateService: AuditTemplateService): AsyncValidatorFn {
      console.log("Static factory call");
      
      return (control: AbstractControl): Observable<ValidationErrors | null> => {
        if(isEmptyInputValue(control.value)) {
            return of(null);
        } else {
            return control.valueChanges.pipe(
                debounceTime(500),
                distinctUntilChanged(),
                switchMap((name: string) => 
                    auditTemplateService.isNameUnique(name)
                        .pipe
                        (
                            tap(response => console.log('inside switchmap', response)),
                            map(isUnique => !isUnique ? { 'duplicate' : true } : null),
                            catchError(() => of(null))
                        )
                )
            );
        }
      };
    }
  }

  function isEmptyInputValue(value: any): boolean {
      return value === null || value.length === 0;
  }

在模板 html 中,如果我尝试显示错误,它不会显示任何内容:

<span>Duplicate: </span>{{templateNameField.errors?.duplicate}}<br>

谢谢

【问题讨论】:

    标签: rxjs angular-reactive-forms angular11


    【解决方案1】:

    每次更改AbstractControl 状态时都会使用AsyncValidators,因此您不需要使用control.valueChanges observable。

    此外,您从验证器函数返回的 observable 应在发送 null 或错误后发送完整信号。如果你返回一个 hot observable,那么异步验证器将不起作用。

    尝试将control.valueChanges.pipe( 替换为of(control.value).pipe(。此外,如果您的服务方法 .isNameUnique() 没有发出完整的信号,请在您的第一个 tap() 运算符之前添加 take(1)。

    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      if (isEmptyInputValue(control.value)) {
        return of(null);
      } else {
        return of(control.value).pipe(
          distinctUntilChanged(),
          debounceTime(500),
          switchMap((name: string) =>
            auditTemplateService.isNameUnique(name).pipe(
              take(1),
              tap((response) => console.log("inside switchmap", response)),
              map((isUnique) => (!isUnique ? { duplicate: true } : null)),
              catchError(() => of(null))
            )
          )
        );
      }
    };
    

    【讨论】:

    • 另外,您可以将filter((name:string)=&gt;!!name) 添加到of(control.value) observable,而不是使用 if/else 条件。双键将过滤任何虚假字符串值,包括 null 和 ""。
    猜你喜欢
    • 1970-01-01
    • 2014-04-05
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2018-12-29
    • 2019-01-25
    • 1970-01-01
    相关资源
    最近更新 更多