【问题标题】:Adding the displayName whilst using createUserWithEmailAndPassword在使用 createUserWithEmailAndPassword 时添加 displayName
【发布时间】:2016-05-24 12:08:00
【问题描述】:

我想将显示名称添加到刚刚创建的用户。但是当我 createUserWithEmailAndPassword 它说我的 currentUser 为空。有什么问题吗?

var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
  // Sign in with email and pass.
  // [START createwithemail]
  firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // [START_EXCLUDE]
    if (errorCode == 'auth/weak-password') {
      alert('The password is too weak.');
    } else {
      console.error(error);
    }
    // [END_EXCLUDE]
  });
  // [END createwithemail]
  var user = firebase.auth().currentUser;
  user.updateProfile({
      displayName: username
    }).then(function() {
      // Update successful.
    }, function(error) {
      // An error happened.
  });
document.getElementById("submitButton").innerHTML = "Loading...";
$("#submitButton").css("background-color", "#efefef");
$("#submitButton").css("cursor", "init");
$("#submitButton").css("color", "#aaa");
registerUserToDB(username, name, email);
console.log("shouldhave worked");

【问题讨论】:

    标签: javascript firebase


    【解决方案1】:

    createUserWithEmailAndPassword 是一个异步调用,与 Firebase 中的几乎所有其他函数一样。您创建了用户(很可能成功),但在您尝试获取currentUser 之后立即创建。在几乎所有情况下,您都会尝试在 Firebase 完成创建用户之前获取 currentUser

    在回调内部重写:

    firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
        // [END createwithemail]
        // callSomeFunction(); Optional
        // var user = firebase.auth().currentUser;
        user.updateProfile({
            displayName: username
        }).then(function() {
            // Update successful.
        }, function(error) {
            // An error happened.
        });        
    }, function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // [START_EXCLUDE]
        if (errorCode == 'auth/weak-password') {
            alert('The password is too weak.');
        } else {
            console.error(error);
        }
        // [END_EXCLUDE]
    });
    

    .then 将在成功时调用,function(error) 将在错误时调用。您想在用户创建成功后设置您的用户。

    有些人不喜欢嵌套回调,因此您可以创建一个获取当前用户并在成功时调用该函数的函数。

    文档:

    Firebase Promises

    Async, callbacks

    【讨论】:

    • 好的提示与 .then(function(){...});很好并且可以工作,但是用户,updateProfile 没有...如果我对当前用户运行检查,它会将 displayName 显示为 null,另外我无法让 .set 函数为数据库工作....有什么提示吗?
    • 试试我的新答案,user 被传递到成功回调而不是erroruser 用于设置displayName
    • 好的,所以我试过了,当提醒用户你得到 [Object object] 时会发生什么......之后调用 updateProfile 函数......当我提醒错误消息时这就是它所说的:错误:发生了网络错误(例如超时、中断连接或无法访问的主机)。
    • 你发现了吗?我也不能让它工作
    • 我相信promise传递了一个UserCredential实例,所以你需要做.then((userCred) => { userCred.user.updateProfile({...}) })
    【解决方案2】:

    你必须这样做。

    import {AngularFireAuth} from '@angular/fire/auth';
    import { auth } from 'firebase';
    
    constructor(private auth: AngularFireAuth) {}
    
    signup(username: string, email: string, password: string) {
      this.auth.auth.createUserWithEmailAndPassword(email, password)
      .then((user: auth.UserCredential) => {
        user.user.updateProfile({
          displayName: username
        });
      })
    }
    

    如果您使用 Angular,则可以使用依赖注入将 AUTH 实例注入构造函数,然后访问 AUTH 服务 (this.auth.Auth),并使用 createUserWithEmailAndPassword() 方法创建您的帐户。成功创建帐户后,它会返回 Promise。由于它包含在 Promise 中,因此您必须使用 async、await 或 then() 来访问 UserCredential 类型的值。 UserCredential 的界面如下。

    UserCredential: { additionalUserInfo?: AdditionalUserInfo | null; credential: AuthCredential | null; operationType?: string | null; user: User | null }
    

    如您所见,UserCredential 实例中有许多属性,其中之一是 USER(用户:User | null)。该属性包含用户的所有信息。现在您可以访问 firebase.User 的方法。负责更新用户配置文件的方法是 updateProfile()。它具有 displayName、PhotoURL 属性。现在您可以像这样更新 userProfile。 user.user.updateProfile({ displayName: NAME })。请记住,您必须更新括号 ( {} ) 内的属性,因为 updateProfile 支持 JavaScript 对象参数。该对象有两个属性,分别称为 displayName 和 photoURL。

    updateProfile ( profile :  { displayName ?: string | null ; photoURL ?: string | null } ) : Promise < void >
    

    https://firebase.google.com/docs/reference/js/firebase.auth.Auth https://firebase.google.com/docs/reference/js/firebase.auth#usercredential https://firebase.google.com/docs/auth/web/password-auth#create_a_password-based_account https://firebase.google.com/docs/reference/js/firebase.User#updateprofile

    【讨论】:

      【解决方案3】:

      对于使用新 SDK 的任何人,您都可以在 Angular 中执行以下操作:

      import {
        ...
        createUserWithEmailAndPassword,
        updateProfile,
      } from '@angular/fire/auth';
      
      signup(username: string, email: string, password: string, displayName: string): Promise<void> {
        createUserWithEmailAndPassword(this.auth, email, password).then(
         userCred => {
           updateProfile(userCred.user, { displayName });
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-11-26
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2019-05-18
        相关资源
        最近更新 更多