簡體   English   中英

Angular 中的異步電子郵件驗證

[英]Asynchronous email validation in Angular

我想編寫一種方法來驗證 Firebase 身份驗證數據庫中是否已存在電子郵件。 因此,如果用戶鍵入電子郵件,則應檢查數據庫是否已存在。 如果是這樣,我想使用 FormControl 以 HTML 格式顯示消息。

這是我編寫的方法的代碼:

checkEmail(control:FormControl): Promise<any> | Observable<any>{
    const answer = new Promise<any>((resolve, reject) => {
      setTimeout(() => {
        if(control.value === "someone@hotmail.com"){
          resolve({'emailTaken': true})
        }else{
          resolve(null);
        }
      },1500);
    });
    return answer;
  }

如您所見,它正在檢查靜態值(“someone@hotmail.com”)。 如果該電子郵件已經存在,我希望能夠檢查我數據庫中的所有用戶。 我在想也許我可以通過獲取數據庫中所有用戶的列表來解決這個問題,將它們放在一個列表中,然后遍歷列表以查看電子郵件是否等於用戶輸入。 但是我還沒有為此找到一個 Firebase 函數,因此我們將不勝感激!

*編輯:這是我的服務代碼:

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
import { LoginComponent } from './login/login.component';
import { stringify } from 'querystring';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  token:string;

  constructor(private router: Router) {

    if(localStorage.getItem('token')) {
      this.token = localStorage.getItem('token');
    }

   }

  signup(email:string, passwd:string){
    firebase.auth().createUserWithEmailAndPassword(email, passwd).catch(
      error=> console.log(error)
    );
  }

  isLoggedIn(){
    return localStorage.getItem('token');
  }

  login(email:string, passwd:string){
    return firebase.auth().signInWithEmailAndPassword(email, passwd).then( 
      () => {
        firebase.auth().currentUser.getIdToken().then((token:string) => {
          this.token = token;
          localStorage.setItem('token', token);
        });
        this.router.navigateByUrl('');
        return true;
      }).catch(
        error => {
          console.log(error);
          return false;
        }

      );
  }

  getToken(){
    firebase.auth().currentUser.getIdToken().then(
      (token:string) => this.token = token
    );
    return this.token;
  }

  logout(){
    firebase.auth().signOut();
    this.token = null;
    localStorage.removeItem('token');
    this.router.navigate(['/Login']);
  }
}

您絕對應該創建一個調用 FireBase 的服務。 在您的代碼片段中,您沒有發送任何請求。 創建服務后,您應該使用.valueChanges訂閱您的輸入字段,並在.subscribe方法中通過服務檢查它的有效性。

要檢查用戶是否已使用給定的電子郵件地址注冊,請調用fetchSignInMethodsForEmail方法 有關如何調用此方法的示例,請參閱 Firebase 文檔關於區分不同提供商的帳戶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM