繁体   English   中英

如何从 Firebase 获取 displayName?

[英]How do i get displayName from Firebase?

我一直无法从 Firebase 中获取显示名称。 下面是注册过程编码

 const promise = auth.createUserWithEmailAndPassword(email, pass)
 .then(
    (user)=>{
   // here you can use either the returned user object or       
 firebase.auth().currentUser. I will use the returned user object
      if(user){
        user.updateProfile({
           displayName: textUsername.val(),
        //    photoURL: // some photo url
        })
      }
  })
  .then( function() {
      console.log('User Name Set!')
  })
  .catch(function() {
    console.log('error')
  });
 promise.catch(e => console.log(e.message));

 })

 firebase.auth().onAuthStateChanged(firebaseUser => {
  if(firebaseUser) {
      console.log(firebaseUser)
  } else {
    console.log('not logged in');
  }
 })

console.log 显示“用户名设置!” 并且 console.log(firebaseUser) 显示在 currentUser 的数据库中设置了 displayName,并且名称是我所期望的。 然而,

console.log(firebase.auth().currentUser) 

给出空值,并且

if (user != null) {
    console.log(user.displayName);
}

这也返回为空。

我一直在寻找获取 firebase 数据集数据的方法,但我无法做到。

如果有人能给我任何建议,那就太好了。

谢谢你。

firebase.auth().currentUser.displayName返回 OAuth 提供者的显示名称。 但是, firebase.auth().currentUser异步解析并且在页面加载时为空/空。 如果您将console.log(firebase.auth().currentUser.displayName)放在.onAuthStateChanged您会看到。

我最终使用递归来解决这个问题。 我希望有一种更优雅的方式,但这是唯一对我有用的方法。 如果您用不同的解决方案解决了这个问题,请分享!!

我需要这个来创建新用户。 当有人登录时,它似乎永远不会返回 null。

setTimeout() 将递归减慢了 0.5 秒,这样您就不会因多次调用该函数而出错。 您可以通过调整毫秒来加快或减慢速度。

工作代码:

auth.onAuthStateChanged(user => {
    if (user) {
      // Everything inside here happens if user is signed in
      console.log(user)

      // Greet the user with a message and make it personal by using their display name
     injectDisplayName = () => {
          if(firebase.auth().currentUser.displayName === null){
              console.log('happens');
              setTimeout(() => {
                injectDisplayName()
            }, 500)
          } else {
              document.getElementById('display-name-header').textContent = `Hello, ${firebase.auth().currentUser.displayName}`
          } 
      }
      injectDisplayName()

    } else {
      // Everything inside here happens if user is not signed in
    }
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM