无法设置 angular 异步验证器

Can't set angular async validator

我根据文档创建了以下 angular 异步验证器 class:

import { Injectable } from '@angular/core';
import {
  AsyncValidator,
  AbstractControl,
  ValidationErrors,
} from '@angular/forms';
import { XService } from '../../pages/x/x.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class UniqueXValidator
  implements AsyncValidator {
  constructor(
    private xService: XService,
  ) {}

  validate(ctrl: AbstractControl): Observable<ValidationErrors | null> {
    return this.xService.checkExists(ctrl.value).pipe(
      map(exists =>
        exists ? { uniqueX: true } : null,
      ),
      catchError(() => of(null)),
    );
  }
}

然后我尝试以这种方式以编程方式将其附加到表单控件:

    this.form.controls['code'].setAsyncValidators(
      UniqueXValidator,
    );

在第二段代码中将“UniqueXValidator”悬停时,我收到以下错误消息显示为工具提示:

    Argument of type 'typeof UniqueXValidator' is not assignable to parameter of type 'AsyncValidatorFn | AsyncValidatorFn[]'.
  Type 'typeof UniqueXValidator' is missing the following properties from type 'AsyncValidatorFn[]': pop, push, concat, join, and 25 more.ts(2345)

编辑: 这可能是我的 angular 版本 (7) 和文档 (11)

之间的兼容性问题

setAsyncValidators 期望数组不是单个验证器

你也不需要 @Injectable() UniqueXValidator

像这样使用 AsyncValidatorFn 而不是 AsyncValidator:

usernameValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return this.checkIfUsernameExists(control.value).pipe(
      map(res => {
        // if res is true, username exists, return true
        return res ? { usernameExists: true } : null;
        // NB: Return null if there is no error
      })
    );
  };
}

那么你可以在初始化时添加一个验证器:

this.fb.group({
  username: [
    null, [Validators.required],  [this.usernameService.usernameValidator()]
  ]
});

或在运行时:

this.form.controls['code'].setAsyncValidators(
  this.usernameService.usernameValidator()
);