1

我按照文档创建了以下角度异步验证器类:

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”悬停在第二段代码中时,我收到以下错误消息,显示为 vs 代码的工具提示:

    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)

编辑:这可能是我的角度版本(7)和文档(11)之间的兼容性问题

4

2 回答 2

3

像这样使用 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()
);
于 2021-05-06T06:54:16.610 回答
0

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

@Injectable()你也不 需要UniqueXValidator

于 2021-05-06T06:54:12.927 回答