Angular 4: reactive form control is stuck in pending state with a custom async validator

后端 未结 3 1629
无人及你
无人及你 2020-12-31 00:02

I am building an Angular 4 app that requires the BriteVerify email validation on form fields in several components. I am trying to implement this validation as a custom asyn

3条回答
  •  醉梦人生
    2020-12-31 00:29

    There's a gotcha!

    That is, your observable never completes...

    This is happening because the observable never completes, so Angular does not know when to change the form status. So remember your observable must to complete.

    You can accomplish this in many ways, for example, you can call the first() method, or if you are creating your own observable, you can call the complete method on the observer.

    So you can use first()

    UPDATE TO 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())
        }
      }
    }
    

    A slightly modified validator, i.e always returns error: STACKBLITZ


    OLD:

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

    A slightly modified validator, i.e always returns error: STACKBLITZ

提交回复
热议问题