为什么我的异步验证器似乎无法工作?

问题描述 投票:0回答:1

我创建了简单的反应式表单,我想使用异步验证器。为此,我使用 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 };

这是一个现场演示

angular angular-reactive-forms
1个回答
0
投票

您所说的异步验证器实际上是异步验证器的工厂(返回异步验证器的函数)。因此,立即修复代码的方法是将

this.customValidator
替换为
this.customValidator()
。但由于您的工厂不接受任何参数,您也可以将
asyncValidator(): AsyncValidatorFn
的签名更改为
asyncValidator(): Observable<ValidationErrors | null>
并相应地更改实现。

© www.soinside.com 2019 - 2024. All rights reserved.