Angular 自定义异步验证器保持挂起状态 [英] Angular Custom Async Validator stays in pending state

查看:38
本文介绍了Angular 自定义异步验证器保持挂起状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义验证器来验证用户的电子邮件是否唯一.

I have a Custom Validator that validates if a user's email is unique or not.

我在 stackoverflow 和互联网上搜索了相关主题,但没有帮助

当我在表单中提供输入(发送请求)时,请求保持挂起状态并且没有解决.

when I'm giving input in the form (sending the request), the request stays at pending state and doesnot resolves.

我已经在 postman 中测试了后端,它按预期工作,问题出在客户端或角度方面.

I've tested the backend in postman, its working as expected, the problem is at client or angular side.

验证函数如下:

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

当我更改表单控件的值时,会出现挂起的类,但它会一直存在而不是得到解决.

When i'm changing the form control's value, the pending class appears, but it sticks in forever instead of getting resolved.

我的电子邮件表单控件如下:

I have the email form control as follows:

'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 });
  }

为什么验证器没有及时解决并一直处于待处理状态?

Why The validator is not resolving in time and staying pending forever?

以下代码从服务中获取价值就好了,我已经通过将响应记录到控制台中来检查它.

The following code is getting value from the service just fine, i've checked it by logging the response into the console.

如果电子邮件不存在于数据库中,那么它会得到很好的解析,但如果电子邮件已经存在,它会抛出一个错误并且状态保持挂起.

If the email is not present in the database, then it is getting resolved just fine, but if the email is already present, it is throwing an error and the state remains pending.

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

推荐答案

可观察对象永远不会完成.

The observable never completes.

尝试在末尾添加 .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();
 }

这篇关于Angular 自定义异步验证器保持挂起状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆