angular - Angular 7:自定义异步验证器
问题描述
我正在尝试为我的注册表单创建一个自定义异步验证器,用于检查电子邮件是否已存在。如果电子邮件不存在,则后端返回 404,如果存在则返回 200(无法更改此旧代码)。
我找到了一些教程,但没有找到使用最新 rxjs 库的教程。我创建了这个验证类:
export class UniqueEmailValidator {
static createValidator(httpClient: HttpClient, degree: number, wlId: number) {
return (control: AbstractControl) => {
return httpClient.get(`${url}?degree=${degree}&email=${control.value}&wl_id=${wlId}`)
.pipe(
map(
(response: Response) => {
return response.status === 404 ? null : { emailNotUnique: true };
}
)
);
};
}
}
并在我的 ts 文件中创建我正在使用的表单
this.registerForm = this.fb.group({
email: ['', [Validators.required, Validators.email], UniqueEmailValidator.createValidator(
this.httpClient, this.wlService.wl.degree, this.wlService.wl.id)],
xhr 调用正在完成并正确返回,但电子邮件的表单控制仍处于待处理状态。关于我做错了什么有什么想法吗?
解决方案
经过一段时间和更多研究后想通了。
验证类:
@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返回一个observable。
然后在我正在做的表单创建中:
this.registerForm = this.fb.group({
email: ['', [Validators.required, Validators.email], this.uniqueEmailValidator.createValidator(
this.wlService.wl.degree, this.wlService.wl.id
)],
我在模块中添加了 UniqueEmailValidator 作为提供者并注入到这个组件构造函数中。
推荐阅读
- mysql - MySQL DATE_ADD() 不工作
- c# - iText 7 Asp.Net 无法打开 Pdf(损坏)
- jquery - 知道2个输入滑块jquery之间的值
- android - 迭代 RecyclerView 中的所有项目
- neo4j - 在 neo4j 中,我们可以将持续时间转换为秒吗?
- jquery - 在 functions.php 和 AJAX 请求中发布元数据
- r - 如果满足条件,则在 R 中绘制一条垂直线
- asp.net - Angular 5 不会发回 auth cookie
- python - Flask CLI 命令不在 __init__.py 文件中
- ansible - juniper_junos_software 安装软件但由于“没有处理程序..”而导致任务失败