角度自定义异步验证器未显示错误

时间:2019-08-20 15:01:38

标签: angular observable angular-custom-validators

当我实际进行异步调用时,我的异步验证器不起作用(但是当我用Observable.of(result)对其进行模拟时,它可以工作。html看起来像这样:

   <div class="form-group">
          <label for="emailAddress" class="control-label">Email</label>
          <input type="email"
                 id="emailAddress"
                 class="form-control"
                 [(ngModel)]="parent.EmailAddress"
                 name="emailAddress"
                 [ngModelOptions]="{updateOn: 'blur'}"
                 appDuplicateEmailValidator
                 #emailAddress = "ngModel">
        </div>

有问题的验证者是appDuplicateEmailValidator

验证代码如下:

  public validate(control: AbstractControl): Observable<ValidationErrors | null> {
    // return observableOf({ 'isDuplicateEmail': true });

    return this.checkForDupeUserAndGetValidationState(emailAddress);
  }

  private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
    const validationStateObs: Observable<ValidationErrors | null> = new Observable(observer => {
      this.adminService.getUser(emailAddress).subscribe(
        (res: any) => {
          const validationState = !!res ? observableOf({ 'isDuplicateEmail': true }) : null;
          console.log('Observer next, validation state: ', validationState); // Gets correct val state
          observer.next(validationState);
          console.log('Is it hitting this'); // Gets hit
        }, (err) => {
          observer.next(null);
        });
    });

重要的一点是,当我取消注释// return observableOf({ 'isDuplicateEmail': true });时,一切都会按预期进行。但是,即使您看到的是返回正确的值(将其记录为使用过的调试器),也无法通过上述方式查看上面的代码。 “无效”是指表单控件永远不会进入错误状态,如下所示:

<pre>IS INVALID: {{emailAddress.invalid}}</pre>
<pre>ERRORS: {{emailAddress.errors | json}}</pre>

为什么以及如何解决?

3 个答案:

答案 0 :(得分:1)

问题是,为什么您要订阅然后以新的Observable形式返回?我认为您应该能够做到这一点:

private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
    return this.adminService.getUser(emailAddress).pipe(map(
      (res: any) => {
        return !!res ? { 'isDuplicateEmail': true } : null;
      }, catchError(err => {
        return of(null);
      })));
  }

这样,您将让异步验证器自己为您处理订阅...

希望这对您有帮助...

答案 1 :(得分:1)

您有3期。 1.您需要实际返回可观察值2.您正在通过观察者发送一个可观察值而不是一个值3.该可观察值需要完成。

您可以这样做:

  private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
    const validationStateObs: Observable<ValidationErrors | null> = new Observable(observer => {
      this.adminService.getUser(emailAddress).subscribe(
        (res: any) => {
          const validationState = !!res ? { 'isDuplicateEmail': true } : null; // just send the value
          observer.next(validationState);
          observer.complete(); //complete here
        }, (err) => {
          observer.next(null);
          observer.complete(); // and complete here
        });
    });
    return validationStateObs; // return it here
  }

但是更简便,更清洁的方法是从服务中返回响应并使用运算符,而不是创建一个可观察的对象并将其嵌套在其中。

  private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
    return this.adminService.getUser(emailAddress).pipe(
      map((res: any) => !!res ? { 'isDuplicateEmail': true } : null),
      catchError((err) => observableOf(null))
    )
  }

http的可观察对象在一次发射后自然完成,因此您不必担心完成或您遇到的其他任何复杂逻辑。

答案 2 :(得分:0)

observableOf({ 'isDuplicateEmail': true })返回的是Observable权利?您应该将普通方法放在observer.next()中,而不是可观察的。

尝试删除observableOf并进行测试。 应该是这样的:

  private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
    const validationStateObs: Observable<ValidationErrors | null> = new Observable(observer => {
      this.adminService.getUser(emailAddress).subscribe(
        (res: any) => {
          const validationState = !!res ? { 'isDuplicateEmail': true } : null;
          console.log('Observer next, validation state: ', validationState); // Gets correct val state
          observer.next(validationState);
          console.log('Is it hitting this'); // Gets hit
        }, (err) => {
          observer.next(null);
        });
    });

我希望它能这样工作