Angular 5 | 检查Firebase中是否存在字段

F3L*_*NYR 6 javascript forms validation angular google-cloud-firestore

我目前正在开发一个大型项目,为此我需要使用Firebase和Angular 5,但我阻止了一些关于表单验证的问题.我解释一下,我想创建一个自定义验证器来检查用户输入的电子邮件是否已被使用.为此,我在自定义验证器中放置了一个函数,当电子邮件已经被使用时会显示错误,但是当我们输入未使用的地址时会出现问题.

当我使用已经使用过的地址验证表单时,表单会返回状态:"INVALID",这很正常,这就是我要查找的内容,但是当我使用不在Firestore中的电子邮件进行验证时,它会返回错误告诉我表单处于"PENDING"状态,也就是说等待......但是等待什么?

我所做的

我在模板中创建了formControl

// inscription.component.html
<mat-step [stepControl]="form">
  <form [formGroup]="form">
    <mat-form-field>
       <input matInput formControlName="email" 
       placeholder="Ton adresse email" required>
       <mat-error *ngIf="email.invalid">
         {{ getErrorMessage(email, 'adresse email', 3, 25) }}
       </mat-error>
    </mat-form-field>
  </form>
</mat-step>
Run Code Online (Sandbox Code Playgroud)

我的函数getErrorMessage()

// inscription.component.html
getErrorMessage(selector: any, element: string, minCharacters: number, maxCharacters: number) {
     return selector.hasError('required') ? 'Tu dois entrer ton ' + element :
            selector.hasError('notunique') ? 'Cette ' + element + ' est déjà utilisée' :
            '';
}
Run Code Online (Sandbox Code Playgroud)

我初始化创建表单所需的一切:

// inscription.component.ts
form: FormGroup;
email = new FormControl('', [
   Validators.required,
   Validators.email,
   Validators.minLength(3),
   Validators.maxLength(25)
   // Fonction pour la vérif de l'email
], this.checkIfEmailExistsInDatabase.bind(this));
Run Code Online (Sandbox Code Playgroud)

然后我在表单中初始化formControl"email"

// inscription.component.ts
ngOnInit() {
   this.form = new FormGroup({
      email: this.email,
   });
}
Run Code Online (Sandbox Code Playgroud)

最后......"虫子"来自哪里:

// inscription.component.ts
    checkIfEmailExistsInDatabase(control: AbstractControl) {
        return new Promise(resolve => {
            // We check that there is no document with the same name of what is in the formControl
            firebase.firestore().collection('items').where('email', '==', control.value).get()
                .then(snapshot => {
                    snapshot.forEach(doc => {
                        if (!doc.exists) {
                            console.log('Email doesn\'t exists');
                            resolve(null);
                            // ERROR: Validation status remains in "PENDING"                                // While he must normally proceed to the next step
                        } else {
                            console.log('Email exists already');
                            resolve({ 'notunique' : true });
                            // An error message is displayed well and blocks validation                            }
                    })
                });
        });
    }
Run Code Online (Sandbox Code Playgroud)

我承认我不明白为什么我不明白我可以在哪里得到这个bug,如果它是一个bug,以及如何解决它..:?

抱歉我的英语不好,我是法国人.

如果您有任何想法请不要犹豫,请提前谢谢!