可以通过在AsyncValidator中使用Promise来返回错误消息。以下是一个示例:
import { Injectable } from '@angular/core';
import { AsyncValidator, FormControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class UniqueNameAsyncValidator implements AsyncValidator {
validate(
ctrl: FormControl
): Promise<{ [key: string]: any } | null> | Observable<{ [key: string]: any } | null> {
return this.checkName(ctrl.value).pipe(
map((res) => {
// name is available
return null;
}),
catchError((err) => {
// name is not available
return of({ nameTaken: true });
})
);
}
checkName(name: string): Observable {
// send request to server to check if the name is taken
// return true if available, false otherwise
return of(true);
}
}
在这个示例中,我们可以从服务器端发送请求来检查名称是否被占用。如果名称不可用,则返回一个包含 nameTaken: true 的对象以表示出错。备注:您需要替换checkName方法以实现发送请求的功能。