我将 Angular 与 Firestore 数据库(使用 Angularfire2)一起使用。为了检查用户名是否已经存在,我创建了一个带有验证功能的自定义验证类。不幸的是,无论验证函数返回 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)])],
});
异步验证器是表单控件的第三个参数。
此外,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 }) )
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句