【问题标题】:Cannot read property 'userService' of undefined - implementing async validator (Angular 12)无法读取未定义的属性“userService”-实现异步验证器(Angular 12)
【发布时间】:2021-10-30 15:04:03
【问题描述】:

过去几天我一直在尝试实现异步验证。但是没有一个教程/解决方案有效!

服务代码-

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.validate]]})
}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
    console.log(control.value);
    return of(control.value)
      .pipe(
        delay(10),
        switchMap((value) =>
          this.userService.getUserIdToCheckDuplicate(value).pipe(map(x => {
            return x.exists ? { exists: true } : 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" *ngIf="!data">
          <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?.exists">Already
                      Exists !</div>
     </mat-form-field>

在控制台中- console error

在控制台中,当我在输入中写一些东西时,every key storke 它会打印值,但之后会告诉 值未定义!

这个错误背后的原因是什么?我该如何解决这个问题?它应该可以正常工作,以便 异步验证器 也能正常工作。

谁能帮我解决这个问题?

【问题讨论】:

  • 这可能是this 没有指代组件 - 在return of 的scope 内。可以调试一下吗?
  • 在return of(control.value)中,值是我输入的。当我输入'a'时,它显示'a'。但继续后它最终显示错误。
  • 请参阅下面的答案,正如我所说,this 不在您的范围内。这就是错误的原因。

标签: angular typescript validation rxjs angular-reactive-forms


【解决方案1】:

我已经设法重现了下面stackblitz中的错误

问题是this在这个上下文中没有引用类

一个简单的解决方案是简单地使用箭头函数进行验证

validate = (control: AbstractControl): Observable<ValidationErrors | null> => {
    console.log(control.value);
    return of(control.value)
      .pipe(
        delay(10),
        switchMap((value) =>
          this.userService.getUserIdToCheckDuplicate(value).pipe(map(x => {
            return x.exists ? { exists: true } : null;
          }))
        )
      );
  }

看到这个Here

【讨论】:

    【解决方案2】:

    比这一切都简单:

    validate = (
        control: AbstractControl
      ): Observable<ValidationErrors | null> => {
        return this.userService.getUserIdToCheckDuplicate(control.value).pipe(
              map(x => {
                return x? { exists: true } : null;
              })
          
        );
    

    (*)如果没有重复,我想你的服务返回 null

    见stackblitz(检查,“傻瓜”是重复的)

    如果您使用的是材料

      <mat-form-field class="name" appearance="outline">
        <input matInput placeholder="Name" formControlName="userId">
        <mat-error *ngIf="form.get('userId')?.hasError('required')">
          Name is required*
        </mat-error>
        <mat-error *ngIf="form.get('userId')?.hasError('exists')">
          Name repeat
        </mat-error>
        <mat-hint *ngIf="form.get('userId')?.pending">Validating...</mat-hint>
      </mat-form-field>
    

    但是检查错误'onblur'很好(否则错误不会由缺陷显示:在材料中,如果我们不使用自定义错误匹配器,则只有在触摸formControl时才会显示错误(编辑和模糊)

    this.form = this.fb.group({
      userId: ['', [Validators.required], [this.validate]]
    },{updateOn:'blur'});
    

    【讨论】:

    • 它总是显示“名称重复”消息,即使它不存在于数据库中。这就是问题所在,我已经尝试并遵循了几乎所有的教程和博客;但这些还没有帮助我完成这个异步验证。
    • @Valkyrie_30,如果用户存在,您的服务会返回什么?如果不存在怎么返回?
    • 返回类型为bool,不存在返回false,存在返回true
    • 然后像我一样使用地图:pipe(map(x =&gt; {return x? { exists: true } : null;}),您可以使用“tap”查看是否工作pipe(tap(x=&gt;{console.log("response:",x)}),map(x =&gt; {return x? { exists: true } : null;})
    • i.stack.imgur.com/oq6eM.png 第一个响应是输入的数据存在于数据库中。第二个用于输入数据在数据库中不存在时。 但是,在这两种情况下都显示“名称重复”! (我用过'tap')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2021-02-24
    相关资源
    最近更新 更多