0

内部服务-

getUserIdToCheckDuplicate(userId:any):Observable<any>{
    const url = ``; //url goes here
    return this.http.get<any>(url);
  }

内部组件-

ngOnInit(): void {
    this.form = this.fb.group({
      userId: ['', [Validators.required],[this.existingUserIdValidator()]]
    }

get userId() {
    return this.form.get("userId");
  }

existingUserIdValidator(initialID: string = ""): AsyncValidatorFn {
    return (
      control: AbstractControl
    ):
      | Promise<{ [key: string]: any } | null>
      | Observable<{ [key: string]: any } | null> => {
      if (control.value === initialID) {
        return of(null);
      } 
      else {
        return control.valueChanges.pipe(
          debounceTime(500),
          take(1),
          switchMap(_ =>
            this.userService
              .getUserIdToCheckDuplicate(control.value)
              .pipe(
                map(user =>
                  user ? { existingUserId: { value: control.value } } : null
                )
              )
          )
        );
      }
    };
  }

里面的html-

 <mat-form-field appearance="outline" fxFlex="1 1 calc(25% - 10px)" fxFlex.lt-md="1 1 calc(25% - 10px)"fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color">
    <mat-label class="label-padding">User ID</mat-label>
       <input class="label-padding" formControlName="userId" matInput placeholder="User ID" required />
          <div style="color: red; font-weight: bold;" *ngIf="userId.errors.existingUserId">Already Exists !</div>
 </mat-form-field>

当我开始在输入字段中输入任何内容时,它会显示"Cannot read property 'existingUserId' of null"

我已经按照各种不同的方式来执行这个异步验证。但就我而言,那些从未奏效!我不知道我在哪里犯错误!谁能帮我这个?

4

1 回答 1

0

的类型定义userId.errorsValidationErrors | null。因此,如果没有错误,您将无法访问该existingUserId属性。

你可以这样修复:userId.errors?.existingUserId。如果错误不为空,它只会尝试访问existingUserId 。

关于验证器本身,您无法使用valueChanges. 这是一个解决方案:

import { timer } from 'rxjs';

existingUserIdValidator(initialID: string = ""): AsyncValidatorFn {
    return (
      control: AbstractControl
    ):
      | Promise<{ [key: string]: any } | null>
      | Observable<{ [key: string]: any } | null> => {
      if (control.value === initialID) {
        return of(null);
      } 
      else {
        return timer(500).pipe(
          switchMap(_ =>
            this.userService
              .getUserIdToCheckDuplicate(control.value)
          ),
          map(user => user ? { existingUserId: { value: control.value } } : null
          )
        );
      }
    };
  }

这是一个天真的示例:https ://stackblitz.com/edit/angular-ivy-uv3bv6?file=src%2Fapp%2Fapp.component.html

于 2021-08-31T10:13:28.537 回答