Angular 自定义异步验证器保持挂起状态

2024-05-01

我有一个自定义验证器,可以验证用户的电子邮件是否唯一。

我在 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}));
});

可观察的永远不会完成。

尝试添加.first()在最后。

emailUniqueValidator (control: AbstractControl): Observable<{[key: string]: any}> {
    return this.userService.checkEmailUnique(control.value)
               .map(r => r.json())
               .map(r => (r.found) ? {emailUniqueValidator: true} : null)
               .first();
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 自定义异步验证器保持挂起状态 的相关文章

随机推荐