为什么我的异步验证器似乎不起作用?

Why does my async validator not appear to work?

提问人:Sergey 提问时间:11/16/2023 最后编辑:marc_sSergey 更新时间:11/16/2023 访问量:37

问:

我创建了简单的反应式表单,我想使用异步验证器。为此,我使用了formBuilder的第三个参数。

代码如下:

  ngOnInit() {
    this.form = this.fb.group(
      {
        login: [
          '',
          [Validators.required, this.customValidator],
          [this.asyncValidator()],
        ]
      }],
      }
    );
  }

我的异步验证器函数如下所示:

  asyncValidator(): AsyncValidatorFn {
    console.log('async');
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      console.log('control', control);
      return this.usersService.getUsers().pipe(
        tap(() => console.log('tap')),
        map((users) => {
          console.log(typeof users, users);
          return { usersExists: true }; // i want to launch error
          // return users ? { usersExists: true } : null;
        })
      );
    };
  }

但是,我的异步验证器不起作用,因为在模板中我看到没有键的错误对象。userExists

<pre>{{ form.controls.login.errors | json }}</pre>

请帮我修复我的异步验证器。现在我故意通过以下方式抛出错误:

return { usersExists: true };

这是一个现场演示

角度 反应形式

评论


答:

0赞 Matthieu Riegler 11/16/2023 #1

要使 AsyncValidator 有效,应完成。

  asyncValidator(): AsyncValidatorFn {
    console.log('async');
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      console.log('control', control);
      return this.usersService.getUsers().pipe(
        tap(() => console.log('tap')),
        map((users) => {
          console.log(typeof users, users);
          return { usersExists: true }; 
        }),
        take(1) // Take ensures completion
      );
    };
  }