【问题标题】:Can't set angular async validator无法设置角度异步验证器
【发布时间】:2021-05-06 06:30:49
【问题描述】:

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

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

【问题讨论】:

  • 你需要指定方法
  • 你能解释一下吗? @BojanKogoj

标签: javascript angular typescript angular-forms angular-validator


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    你也不需要@Injectable()UniqueXValidator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多