【发布时间】: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