【问题标题】:displayName always returns null after creating account创建帐户后 displayName 总是返回 null
【发布时间】:2021-01-18 21:15:47
【问题描述】:

我有一个使用 Firebase 作为后端的 Vue 应用程序。新用户注册时使用电子邮件和密码选项。这是firebase方法:

firebase.auth()
          .createUserWithEmailAndPassword(this.user.email, this.user.password)
          .then((res) => {
            res.user
              .updateProfile({
                displayName: this.user.username,
              })
              .then(() => {
              });
          })
          .catch((error) => {
            this.error = error.message;
            console.log("err", error);
          });

在我的 main.js 文件中,我的 onAuthStateChanged 方法如下所示:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log("user", user);
    console.log("nme", user.displayName);
    console.log("email", user.email);
    store.dispatch("fetchUser", user);
  } else {
    store.dispatch("logout");
  }

这个方法当然是在用户注册的时候触发的。问题是我无法访问用户的 displayName 属性,由于某种原因,当用户注册时它总是为空。当我刷新页面时,它具有值,但在注册其 null 并将 null 值作为用户名传递给 Vuex 之后。奇怪的是,例如电子邮件可以立即访问。这是我控制台的截图:

第一部分是"console.log("user", user),然后是其他打印。正如您在用户对象中看到的,displayName 有一个值,但是当我调用 user.displayName 时,它​​的空。

谁能解释一下为什么会这样?提前致谢!

【问题讨论】:

  • 而如果你在调试器里放了一个断点,你在打断点的时候能得到user.displayName吗?

标签: javascript firebase vue.js firebase-authentication


【解决方案1】:

这是因为updateProfile()方法是异步的,不会触发通过onAuthStateChanged()设置的监听器。

因此,当onAuthStateChanged() 监听器在用户创建后立即触发时(并登录,因为在创建用户帐户后,用户也已登录)displayName 的值尚未更新。

updateProfile() 方法返回的承诺得到解决时,您可能应该更新 Vuex Store 中的状态。

大致如下:

  firebase
    .auth()
    .createUserWithEmailAndPassword(this.user.email, this.user.password)
    .then((res) => {
      return res.user.updateProfile({
        displayName: this.user.username,
      });
    })
    .then(() => {
      //Update the Vuex Store here with firebase.auth().currentUser
      console.log(firebase.auth().currentUser.displayName);
    })
    .catch((error) => {
      this.error = error.message;
      console.log('err', error);
    });

【讨论】:

  • 我知道它是异步的,但是当我尝试显示用户对象时,而不仅仅是名称,我可以清楚地看到属性 displayName 具有值并且它也在 onAuthStateChanged() 方法中,所以我怎么可能无法访问属性值?
  • 原因在以下 SO 答案中解释:stackoverflow.com/a/17547032/3371862。如果您执行if (user) {console.log(JSON.stringify(user)); ....,您将看到displayName 的值实际上是null
  • 还可以查看areknawo.com/how-to-properly-log-objects-in-javascript,它解释说这是“由于在扩展树时动态评估的值”。 (即控制台中显示的对象树)
猜你喜欢
  • 2011-06-15
  • 2016-10-06
  • 1970-01-01
  • 2022-01-16
  • 2016-10-02
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
相关资源
最近更新 更多