【问题标题】:Angular 4: reactive form control is stuck in pending state with a custom async validatorAngular 4:反应式表单控件使用自定义异步验证器卡在挂起状态
【发布时间】:2018-07-17 05:49:20
【问题描述】:

我正在构建一个 Angular 4 应用程序,该应用程序需要对多个组件中的表单字段进行 BriteVerify 电子邮件验证。我正在尝试将此验证实现为可与反应式表单一起使用的自定义异步验证器。目前,我可以得到 API 响应,但控制状态卡在挂起状态。我没有收到任何错误,所以我有点困惑。请告诉我我做错了什么。这是我的代码。

组件

import { Component, 
         OnInit } from '@angular/core';
import { FormBuilder, 
         FormGroup, 
         FormControl, 
         Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { EmailValidationService } from '../services/email-validation.service';

import { CustomValidators } from '../utilities/custom-validators/custom-validators';

@Component({
    templateUrl: './email-form.component.html',
    styleUrls: ['./email-form.component.sass']
})

export class EmailFormComponent implements OnInit {

    public emailForm: FormGroup;
    public formSubmitted: Boolean;
    public emailSent: Boolean;
    
    constructor(
        private router: Router,
        private builder: FormBuilder,
        private service: EmailValidationService
    ) { }

    ngOnInit() {

        this.formSubmitted = false;
        this.emailForm = this.builder.group({
            email: [ '', [ Validators.required ], [ CustomValidators.briteVerifyValidator(this.service) ] ]
        });
    }

    get email() {
        return this.emailForm.get('email');
    }

    // rest of logic
}

验证器类

import { AbstractControl } from '@angular/forms';

import { EmailValidationService } from '../../services/email-validation.service';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

export class CustomValidators {

    static briteVerifyValidator(service: EmailValidationService) {
        return (control: AbstractControl) => {
            if (!control.valueChanges) {
                return Observable.of(null);
            } else {
                return control.valueChanges
                    .debounceTime(1000)
                    .distinctUntilChanged()
                    .switchMap(value => service.validateEmail(value))
                    .map(data => {
                        return data.status === 'invalid' ? { invalid: true } : null;
                    });
            }
        }
    }
}

服务

import { Injectable } from '@angular/core';
import { HttpClient,
         HttpParams } from '@angular/common/http';

interface EmailValidationResponse {
    address: string,
    account: string,
    domain: string,
    status: string,
    connected: string,
    disposable: boolean,
    role_address: boolean,
    error_code?: string,
    error?: string,
    duration: number
}

@Injectable()
export class EmailValidationService {

    public emailValidationUrl = 'https://briteverifyendpoint.com';

    constructor(
        private http: HttpClient
    ) { }

    validateEmail(value) {
        let params = new HttpParams();
        params = params.append('address', value);
        return this.http.get<EmailValidationResponse>(this.emailValidationUrl, {
            params: params
        });
    }
}

模板(只是形式)

<form class="email-form" [formGroup]="emailForm" (ngSubmit)="sendEmail()">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <fieldset class="form-group required" [ngClass]="{ 'has-error': email.invalid && formSubmitted }">
                <div>{{ email.status }}</div>
                <label class="control-label" for="email">Email</label>
                <input class="form-control input-lg" name="email" id="email" formControlName="email">
                <ng-container *ngIf="email.invalid && formSubmitted">
                    <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;Please enter valid email address.
                </ng-container>
            </fieldset>
            <button type="submit" class="btn btn-primary btn-lg btn-block">Send</button>
        </div>
    </div>
</form>

【问题讨论】:

  • 尝试订阅表单的 statusChanges 事件,看看它是否始终处于待处理状态,或者在某个时间后将其状态更改为 VALID 或 INVALID 等。
  • 表单状态也卡在pending状态。
  • 我能想到为什么会发生这种情况的唯一原因是因为我使用了switchcMap() 运算符。我知道它用一个新的 observable 替换了当前的 observable。我试图订阅 switchMap() 的输出并从订阅语句中返回一个新的 observable,但这不起作用。它失败并显示类型错误,说它期望验证器函数返回可观察或承诺。

标签: javascript angular angular-reactive-forms angular-validation


【解决方案1】:

有一个gotcha

也就是说,你的 observable 永远不会完成......

发生这种情况是因为 observable 永远不会完成,因此 Angular 不知道何时更改表单状态。所以记住你的 observable 必须完成。

您可以通过多种方式完成此操作,例如,您可以调用 first() 方法,或者如果您正在创建自己的 observable,则可以在观察者上调用 complete 方法。

所以你可以使用first()

RXJS 6 更新:

briteVerifyValidator(service: Service) {
  return (control: AbstractControl) => {
    if (!control.valueChanges) {
      return of(null);
    } else {
      return control.valueChanges.pipe(
        debounceTime(1000),
        distinctUntilChanged(),
        switchMap(value => service.getData(value)),
        map(data => {
          return data.status === 'invalid' ? { invalid: true } : null;
        })
      ).pipe(first())
    }
  }
}

稍作修改的验证器,即总是返回错误:STACKBLITZ


旧:

.map(data => {
   return data.status === 'invalid' ? { invalid: true } : null;
})
.first();

稍作修改的验证器,即总是返回错误:STACKBLITZ

【讨论】:

  • 太好了,很高兴听到! :) :)
  • 希望我能在浪费 6 小时之前找到这个。
  • first() 不再起作用。现在使用管道,但我遇到了与此处提到的完全相同的问题并且找不到修复程序..
  • @xDrago,请重新检查我的答案,我更新了 rxjs 6 的答案 :)
  • 你好,一件事。我正在做类似的事情。但是,当它通过第一个 if 条件进入时,我的表单总是返回待处理。我该怎么办? @AJT82
【解决方案2】:

所以我所做的是在未使用用户名时抛出 404 并使用订阅错误路径来解决 null,当我得到响应时,我解决了一个错误。另一种方法是返回一个填充用户名宽度或空的数据属性 通过响应对象并在 404 中使用该对象

例如

在此示例中,我绑定 (this) 以便能够在验证器函数中使用我的服务

我的组件类 ngOnInit() 的摘录

//signup.component.ts

constructor(
 private authService: AuthServic //this will be included with bind(this)
) {

ngOnInit() {

 this.user = new FormGroup(
   {
    email: new FormControl("", Validators.required),
    username: new FormControl(
      "",
      Validators.required,
      CustomUserValidators.usernameUniqueValidator.bind(this) //the whole class
    ),
    password: new FormControl("", Validators.required),
   },
   { updateOn: "blur" });
}

我的验证器类的摘录

//user.validator.ts
...

static async usernameUniqueValidator(
   control: FormControl
): Promise<ValidationErrors | null> {

 let controlBind = this as any;
 let authService = controlBind.authService as AuthService;  
 //I just added types to be able to get my functions as I type 

 return new Promise(resolve => {
  if (control.value == "") {
    resolve(null);
  } else {
    authService.checkUsername(control.value).subscribe(
      () => {
        resolve({
          usernameExists: {
            valid: false
          }
        });
      },
      () => {
        resolve(null);
      }
    );
  }
});

...

【讨论】:

  • 谢谢你,看来我需要解决这个问题。
【解决方案3】:

我的做法略有不同,但遇到了同样的问题。

这是我的代码以及如果有人需要它的修复:

  forbiddenNames(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve, reject) => {
      setTimeout(() => {
        if (control.value.toUpperCase() === 'TEST') {
          resolve({'nameIsForbidden': true});
        } else {

          return null;//HERE YOU SHOULD RETURN resolve(null) instead of just null
        }
      }, 1);
    });
    return promise;
  }

【讨论】:

  • 老实说,我确实想过在我的自定义验证器函数中使用 setTimeout(),但认为它是一种 hack(而且不是一个好方法),因为我们永远不知道异步 http 调用返回数据需要多长时间。此外,您在看似同步的验证器上使用了 setTimeout()。我不知道你必须实现什么确切的逻辑,但我想它对你有用。 :)
  • @AndreKuzmicheff 我编写该代码仅用于测试,验证器的目的仅存在于此特定问题的上下文中
  • 我明白了。在这种情况下,由于服务器响应时间不同,我仍然会避免将 setTimeout() 用于使用 http 服务的自定义异步验证器。
  • 嗨 @alexlz 感谢您发布此内容,您可以对 observable 做同样的事情吗?
  • @Harsimer 我猜是这样,我认为您只需要创建一个可观察对象而不是 Promise 并调用 next() 而不是 resolve();
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2020-01-13
  • 2018-09-19
  • 2021-01-12
  • 2018-06-16
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
相关资源
最近更新 更多