2016-05-24 1 views
4

作成したばかりのユーザーに表示名を追加したいとします。しかし、私がUserUseEmailAndPasswordを作成するとき、私のcurrentUserはnullです。何か間違っている?createUserWithEmailAndPasswordを使用してdisplayNameを追加する

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"); 

答えて

15

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

+0

.then(関数(){...})といいチップ。私はcurrentuserのチェックを実行し、さらに、データベースのために働く.set関数を取得することはできません....任意のヒントは、displayNameをnullとして表示されますか? – Marc

+0

https://firebase.google.com/docs/auth/web/manage-users – Marc

+1

私の新しい答えを試してください。 'user'は' error'の代わりに成功のコールバックに渡され、 'user'は' displayName' – theblindprophet

関連する問題