经过一段时间和更多研究后弄清楚了。
验证类:
@Injectable()
export class UniqueEmailValidator {
constructor(private http: HttpClient) {}
searchEmail(email: string, degree: number, wlId: number) {
return timer(1000)
.pipe(
switchMap(() => {
// Check if email is unique
return this.http.get<any>(`${url}?degree=${degree}&email=${email}&wl_id=${wlId}`);
})
);
}
createValidator(degree: number, wlId: number): AsyncValidatorFn {
return (control: AbstractControl): Observable<{ [key: string]: any } | null> => {
return this.searchEmail(control.value, degree, wlId)
.pipe(
map(
(response: Response) => {
return null;
},
),
catchError(
(err: any) => {
return err.status === 404 ? of(null) : of({ emailNotUnique: true });
},
),
);
};
}
}
不确定计时器是否可以更改,但我在一篇文章中找到了它,它工作正常。希望得到一些确认。
基本上我正在执行 catchError,因为后端的响应返回 404 并从 catchError 再次返回可观察值。
然后在我正在做的表单创建中:
this.registerForm = this.fb.group({
email: ['', [Validators.required, Validators.email], this.uniqueEmailValidator.createValidator(
this.wlService.wl.degree, this.wlService.wl.id
)],
我将 UniqueEmailValidator 添加为模块中的提供程序,并注入到此组件构造函数中。