【问题标题】:Firebase Auth store firstName and lastName of userFirebase Auth 存储用户的名字和姓氏
【发布时间】:2019-06-05 13:36:25
【问题描述】:

尊敬的 Stackoverflow 社区,

我们使用 Firebase Auth 进行身份验证。为此,我们提供使用 google 和 facebook 的社交登录以及使用电子邮件和密码登录。以下代码显示了以后想要使用电子邮件和密码登录的用户的注册页面。

import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  public emailAddress="";
  public firstName="";
  public lastName="";
  public password="";

  constructor(public afAuth: AngularFireAuth, private router: Router) {
  }

  ngOnInit() {
  }

  reset() {
    this.emailAddress=""
    this.password=""
    this.firstName=""
    this.lastName=""
  }

  register() {
    let emailAddress = this.emailAddress
    let password = this.password
    let firstName = this.firstName
    let lastName = this.lastName
    this.reset()
    console.log(emailAddress)
    console.log(password)
    auth().createUserWithEmailAndPassword(emailAddress, password).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      console.log(errorCode)
      var errorMessage = error.message;
      console.log(errorMessage)
      // ...
    });
  }
}

电子邮件、密码、名字、姓氏的数据来自输入字段,该输入字段通过与组件的数据绑定交换数据。

<input type="email" [(ngModel)]="emailAddress" required>

当我尝试获取用户显示名称时,它仅在用户使用社交提供商登录时才有效。这很明显,因为他在使用电子邮件和密码注册时没有设置它。现在我想问你是否有人知道如何在 firebase 中存储 firstName 和 lastName 以便显示 user.displayName。

<div *ngIf="afAuth.user | async as user; else notAuth">
 Hello {{ user.displayName }}
</div>

【问题讨论】:

  • 成功创建用户后,您需要手动更新该用户的displayName。您可以使用updateProfile()。作为方法,您可以使用createUserWithEmailAndPasswordthen() 来执行updateProfile()

标签: angular firebase firebase-authentication


【解决方案1】:

联合登录与电子邮件/密码登录的操作方式不同,但无论如何,在 firebase.auth() 子系统(Firebase 控制台中的“身份验证”按钮/部分)中创建用户与将数据存储在数据存储,例如实时数据库或 Firestore。所以,这里发生了 2 个单独的事件/事情。

firstNamelastName 只是必须存储在数据存储中的记录。

最佳做法是使用来自firebase.auth().currentUser.uid 的用户uid 作为存储在数据存储中"users" 集合中的用户文档的文档ID。

.onAuthStateChanged 是正确的客户端观察者,用于捕获登录用户的uid。观察者不是同步的 - 因此在用户文档中创建/存储其他用户信息的代码必须从 .onAuthStateChanged 观察者中触发(触发之后,您将拥有一个填充的 user 对象。

【讨论】:

    【解决方案2】:

    如果您使用密码创建用户(即通过调用firebase.auth().createUserWithEmailAndPassword(email, password)),您可以等待承诺解决以更新显示名称。这将通过user 对象的update_profile 方法完成。这是文档的链接:

    https://firebase.google.com/docs/auth/web/manage-users#update_a_users_profile

    更新后,您可以像访问其他身份验证提供商(即 Facebook 或 Google)一样访问displayName

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 2017-06-30
      相关资源
      最近更新 更多