【问题标题】:Angular custom validation with async service使用异步服务的角度自定义验证
【发布时间】:2019-10-03 14:14:39
【问题描述】:

我正在使用 Angular 和 Firestore 数据库(使用 Angularfire2)。为了检查用户名是否已经存在,我创建了一个带有验证函数的自定义验证类。不幸的是,无论 validate 函数返回 null 还是 { emailTaken: true },表单似乎都保持无效。如果我将函数重写为仅返回 null 它可以工作,所以我认为错误位于此函数中 - 也许它与异步有关?

NameValidator 类:

import { FirebaseService } from './../services/firebase.service';
import { FormControl } from "@angular/forms";
import { Injectable } from '@angular/core';

@Injectable()
export class NameValidator {
  constructor(private firebaseService: FirebaseService) { }

  validate(control: FormControl): any {
    return this.firebaseService.queryByUniqueNameOnce(control.value).subscribe(res => {
        return res.length == 0 ? null : { emailTaken: true };
    });
  }
}

firebaseService查询函数:

queryByUniqueNameOnce(uniqueName: string) {
 return this.firestore.collection("users", ref => ref.where('uniqueName', '==', uniqueName))
 .valueChanges().pipe(take(1));
}

表单组:

 this.firstForm = this.fb.group({
  'uniqueName': ['', Validators.compose([Validators.required, this.nameValidator.validate.bind(this.nameValidator)])],
});

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    异步验证器将成为表单控件的第三个参数。

    另外,compose 在最新版本中变得无用。

    'uniqueName': ['', [/*sync validators*/], [this.nameValidator.validate]]
    

    您还必须更改验证功能:

      validate(control: FormControl): any {
        return this.firebaseService.queryByUniqueNameOnce(control.value).pipe(
          map(res => !res.length ? null : ({ emailTaken: true }) )
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2022-01-02
      • 2020-11-27
      相关资源
      最近更新 更多