我按照文档创建了以下角度异步验证器类:
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)之间的兼容性问题