Adding the displayName whilst using createUserWithEmailAndPassword

后端 未结 2 1992
南旧
南旧 2021-02-04 06:20

I want to add the display name to the user that was just created. But when I createUserWithEmailAndPassword it sais my currentUser is null. Anything wrong?

var n         


        
2条回答
  •  你的背包
    2021-02-04 07:15

    You have to do like this.

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

    If you use Angular, then you can use dependency injection to inject an AUTH instance to the constructor, then you access to the AUTH service (this.auth.Auth), and create your account with createUserWithEmailAndPassword() method. Once the account is successfully created, it returns Promise< UserCredential >. Since it's wrapped in a Promise you have to use either async, await, or then() to access to the UserCredential typed value. The interface of UserCredential goes as following.

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

    As you see there are a number of properties in the UserCredential instance, and one of them is USER (user: User | null). This property has all the information of the user. Now you can access to methods of firebase.User. The method responsible for updating the user profile is updateProfile(). It has displayName, PhotoURL properties. Now you can update the userProfile like this. user.user.updateProfile({ displayName: NAME }). Remember you have to update properties inside of parenthesis ( {} ), because updateProfile supports JavaScript object argument. This object has two properties called displayName, and 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

提交回复
热议问题