我有一个自定义验证器,可以验证用户的电子邮件是否唯一。
我在 stackoverflow 和 internet 上搜索了相关主题,但没有帮助
当我在表单中提供输入(发送请求)时,请求保持待处理状态并且不会解析。
我已经在邮递员中测试了后端,它按预期工作,问题出在客户端或角度端。
验证函数如下:
emailUniqueValidator (control: AbstractControl): Promise<{[key: string]: any}> | Observable<{[key: string]: any}> {
return new Promise((resolve, reject) => {
this.userService.checkEmailUnique(control.value).subscribe((response: Response) => {
const body = response.json();
if (body.found === false) {
resolve(null); // email is unique
} else {
reject({emailUniqueValidator: true}); // email is not unique
}
});
});
}
当我更改表单控件的值时,会出现挂起的类,但它会永远保留而不是得到解决。
我的电子邮件表单控件如下:
'email': new FormControl('', [
Validators.required,
Validators.email
], this.emailUniqueValidator.bind(this)
),
我的用户服务如下:
checkEmailUnique (email: string): Observable<Response> {
return this.http.post('http://localhost:3000/user/email', {email}, { withCredentials: true });
}
为什么验证器没有及时解决并永远处于待处理状态?
EDIT:
以下代码可以很好地从服务中获取价值,我已通过将响应记录到控制台来检查它。
如果数据库中不存在该电子邮件,则可以很好地解决该问题,但如果该电子邮件已存在,则会引发错误并且状态仍处于待处理状态。
return new Promise((resolve, reject) => {
this.userService.checkEmailUnique(control.value).subscribe((response: Response) => {
console.log(response);
response.json().found ? reject({emailUniqueValidator: true}) : resolve(null);
}, (error: any) => reject({emailUniqueValidator: true}));
});