无法设置角度异步验证器

问题描述

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

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) 之间的兼容性问题

解决方法

像这样使用 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()
);
,

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

你也不需要@Injectable()上的UniqueXValidator

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...