首页 > 解决方案 > 使用电子邮件和密码进行 Angular6 Firebase 身份验证

问题描述

请帮助我,我是 angular6 firebase 编程的新手。我有很好的带有电子邮件和密码的 Firebase 身份验证系统。但是从注册开始,当我将用户存储在数据库中时,我只能获得 uid 和电子邮件。我对 updateProfile 很感兴趣,但不知道如何在我的代码中实现。我正在使用“@angular/fire”:“^5.0.0”,“firebase”:“^5.5.1”,所以我问这个版本好还是我需要改变。回到问题: 服务:

 import { Injectable } from "@angular/core";
    import { AngularFireAuth } from "@angular/fire/auth";
    import {
      AngularFirestore,
      AngularFirestoreCollection,
      AngularFirestoreDocument
    } from "@angular/fire/firestore";
    import { Observable } from "rxjs";
    import "rxjs/add/operator/map";

    @Injectable()
    export class AuthService {
      constructor(private afAuth: AngularFireAuth, private db: AngularFirestore) {
        // this.afAuth.authState.subscribe(auth => console.log(auth));
      }

      login(email: string, password: string) {
        return new Promise((resolove, reject) => {
          this.afAuth.auth
            .signInWithEmailAndPassword(email, password)
            .then(userData => resolove(userData), err => reject(err));
        });
      }
      getAuth() {
        return this.afAuth.authState.map(auth => auth);
      }
      logout() {
        this.afAuth.auth.signOut();
      }
      register(email: string, password: string) {
        return new Promise((resolove, reject) => {
          this.afAuth.auth
            .createUserWithEmailAndPassword(email, password)
            .then(userData => resolove(userData), err => reject(err));
        });
      }
    }

零件

import { Component, OnInit } from "@angular/core";
import { AuthService } from "../../service/auth.service";
import { Router } from "@angular/router";

@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.css"]
})
export class RegisterComponent implements OnInit {
  email: string;
  password: string;
  constructor(private authService: AuthService, private router: Router) {}

  ngOnInit() {}

  onSubmit() {
    this.authService
      .register(this.email, this.password)
      .then(res => {
        this.router.navigate(["/"]);
      })
      .catch(err => console.log(err.message));
  }
}

我的目标是让 displayName 和 Skill 作为数据库中 User 的属性。使用我的代码注册后 displayName 为空。所以我的问题是如何将 displayName 存储在数据库中?泰维克托。

标签: typescriptfirebasefirebase-authenticationangular6angularfire2

解决方案


欢迎来到 StackOverflow。

原因displayName是 null,因为它默认为 null(除非您从 Facebook 和 Google 等社交网络登录)。你应该考虑做的是:

  • 在每次注册时,在集合内创建一个新文档users(将其命名为您想要的任何名称)。
  • 每次登录时,更新用户的现有文档(您不必这样做,但有时它很有用)。
  • 根据当前认证的用户获取用户文档。

让我们从注册开始:

您有多种登录方法,但我将向您解释它是如何通过电子邮件/密码完成的。

所以首先,我们需要创建register接受电子邮件和密码参数的方法。我看到您已经创建了该方法,但您应该知道您不需要在createUserWithEmailAndPasswordPromise 中限定范围,因为它已经是一个 Promise。用户注册后,我们将他的数据添加到我们的集合中:

register(email: string, password: string) {
  this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then(userCredential => this.upsertUserData(userCredential))
    .catch(error => this.handleAuthError(error);
}

private upsertUserData(userCredential: firebase.auth.UserCredential) {
  // Upsert = Update/Insert.
  return this.afs.doc(`users/${userCredential.uid}`).update({
    email: userCredential.email
  });
}

private handleAuthError(error) {
  console.error(error)
}

如您所见,我创建了另外两个方法,以使该方法register更加简洁易读。

现在我们已经完成了注册,让我们制作登录方法,几乎​​相同:

login(email: string, password: string) {
  this.afAuth.signInWithEmailAndPassword(email, password)
    .then(userCredential => this.upsertUserData(userCredential))
    .catch(error = > this.handleAuthError(error));
}

在我们注册并登录到应用程序之后,我们想要获取用户的数据,以便我们可以这样做:

export class AuthService {

...

user$: Observable<{displayName: string, email: string}> = this.afAuth.authState.pipe(
  switchMap(user => Boolean(user) ? this.afs.doc(`users/${user.id}`).valueChanges() : of(null))
);

...
}

简而言之 -this.afAuth.authState如果用户登录,将发出一个对象。如果用户未登录,则返回 null。user$如果用户登录,则返回用户的文档数据。如果用户不存在(即authState = null),则返回null。


推荐阅读