【发布时间】:2019-07-27 02:38:24
【问题描述】:
我尝试使用自定义验证器来检查电子邮件是否已被占用。 根据文档和一些文章,我想出了这段代码:
在我的 auth.service.ts 中
checkEmail(email) {
const r$ = of(true);
const x$ = of(false);
return this.http.post<any>(`${config.apiUrl}/users/email`, email)
.pipe(
mergeMap(v =>
iif(
() => v,
r$,
x$
)
)
);
}
在我的组件中
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', [
Validators.required,
Validators.email,
this.checkEmail.bind(this)
]]
});
}
checkEmail(control: AbstractControl) {
if (control.value) {
return this.authService.checkEmail({email: control.value}).toPromise()
.then(response => {
return response ? { forbiddenName: {value: control.value}} : null;
});
}
}
但它不起作用,我怎样才能让 checkEmail() 函数为验证器返回正确的数据
【问题讨论】:
-
首先,据我了解,这应该是一个异步验证器:angular.io/guide/form-validation#async-validation 异步验证器在同步验证器之后标记为third argument。
标签: angular typescript validation