【发布时间】:2021-07-22 01:24:17
【问题描述】:
我在 Ionic/Firebase 中遇到了一个问题,验证器的值为反应形式。特别是,我在下面有这 2 个函数,用于检查 firebase 实时数据库中的用户名是否存在。这两个函数返回一个 Promise 布尔值:
export class UsernameValidator {
static async getSnapshot(fc: FormControl){
let isPresent:boolean = false;
await firebase.database().ref().child("users").orderByChild("username")
.equalTo(fc.value)
.once("value", snapshot => {
}).then((data)=> {
if(data.exists())
isPresent = true;
else
isPresent = false;
});
console.log(isPresent);
return isPresent;
}
static async validUsername(fc: FormControl){
try{
let present:boolean =await UsernameValidator.getSnapshot(fc)
if(present==true)
return (null);
else{
return ({validUsername: true});
}
}catch(e){
console.log(e)
}
}
然后,我有一个类,我在其中定义了一个 FormGroup 和验证器:
constructor(private route: ActivatedRoute, private router: Router,
public pfService: ProfileService, public fb: FormBuilder,
public authService: AuthenticationService)
{
this.id = this.authService.userData.uid;
//Underscore and dot can't be next to each other (e.g user_.name).
//Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
this.validPattern = "^(?=.{6,20}$)(?!.*[_.]{2})[a-z0-9._]+$";
this.validPatternName = "^[a-z]{3,10}$";
this.userForm = fb.group({
txtUsername: ["",[Validators.required,Validators.pattern(this.validPattern),
UsernameValidator.validUsername]],
txtName: ["",[Validators.required,Validators.pattern(this.validPatternName)]],
});
this.userForm .valueChanges.subscribe(()=> {
console.log(this.userForm.getError('validUsername'))
})
};
问题是无论 isPresent 的值如何,控制台中的 validUsername 始终为 null,当 isPresent 为 false 时也是如此。我该如何解决这个问题?
【问题讨论】:
标签: javascript ionic-framework firebase-realtime-database async-await customvalidator