代码之家  ›  专栏  ›  技术社区  ›  Paco Zevallos

添加displayName createUserWithEmailAndPassword Firebase Firestore

  •  0
  • Paco Zevallos  · 技术社区  · 6 年前

    我按照本教程在Firebase中创建具有电子邮件和密码的用户: https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/ 具有 createUserWithEmailAndPassword .

    到目前为止,我有这个,它工作正常:

    组件.html

    <form [formGroup]="forma" (ngSubmit)="emailSignUp()" novalidate>
      <!-- <div class="form-group">
        <input type="text" class="form-control" placeholder="Nombre" formControlName="displayName">
      </div> -->
      <div class="form-group">
        <input type="email" class="form-control" placeholder="Email" formControlName="email">
      </div>
      <div class="form-group">
        <input type="password" class="form-control" placeholder="Contraseña" formControlName="password">
      </div>
      <div class="my-2">
        <button class="btn btn-primary btn-block" type="submit" >Crear cuenta</button>
      </div>
    </form>
    

    组件.ts

    this.forma = fb.group ({
      //displayName: ['', Validators.required],
      email: [ '', [Validators.required, Validators.email] ],
      password: [ '', Validators.required ],
    })
    
    emailSignUp() {
      this.auth.emailSignUp(this.forma.value.email, this.forma.value.password)
    }
    

    服务.ts

    interface User {
      uid: string;
      email: string;
      photoURL?: string;
      displayName?: string;
      favoriteColor?: string;
      fechaRegistro?: string;
    }
    
    constructor( private afAuth: AngularFireAuth, private afs: AngularFirestore) { 
      this.user = this.afAuth.authState.pipe(
        switchMap(user => {
          if (user) {
            return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
          } else {
            return of(null)
          }
        })
      )
    }
    
    emailSignUp(email: string, password: string) {
    return this.afAuth.auth
      .createUserWithEmailAndPassword(email, password)
      .then(credential => {
        this.pushUserData(credential.user);
        console.log('Usuario creado')
        this.router.navigate(['/login'])
      })
      .catch(error => {
        this.handleError(error)
      });
    }
    
    private pushUserData( user: User ) {
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
    const data: User = {
      uid: user.uid,
      email: user.email,
    };
    userRef.set(data, {merge: true});
    }
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Sterling Archer    5 年前

    使用updateProfile方法

    register(email:string, password: string, fullname:string){
      return new Promise((resolve, reject) => {
        this.afAuth.auth.createUserWithEmailAndPassword(email, password)
        .then(userData => {
          userData.user.updateProfile({
            displayName: fullname,
            photoURL: ''
          }).then(() => {
            this.updateUserData(userData.user);
            resolve(userData);
          }); 
        },
        err => reject(err))
      });
    }
    
        2
  •  0
  •   Shaytj    6 年前

    只需添加新的输入并将其传递给emailSignUp方法, 将其保存在服务的temperry属性中,并用pushUserData方法将其保存到firestore中

    <div class="form-group">
        <input type="email" class="form-control" placeholder="Email" formControlName="email">
      </div>
    

    组件.ts

    this.forma = fb.group ({
      //displayName: ['', Validators.required],
      email: [ '', [Validators.required, Validators.email] ],
      password: [ '', Validators.required ],
      displayName: [ '', Validators.required ],
    })
    
    emailSignUp() {
      this.auth.emailSignUp(this.forma.value.email, this.forma.value.password, this.forma.value.displayName)
    }
    

    服务.ts

    emailSignUp(email: string, password: string, displayName: string) {
    this._displayName = displayName ;
    return this.afAuth.auth
      .createUserWithEmailAndPassword(email, password)
      .then(credential => {
        this.pushUserData(credential.user);
        console.log('Usuario creado')
        this.router.navigate(['/login'])
      })
      .catch(error => {
        this.handleError(error)
      });
    }
    
    private pushUserData( user: User ) {
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
    const data: User = {
      uid: user.uid,
      email: user.email,
      displayName:this._displayName
    };
    userRef.set(data, {merge: true});
    }
    
        3
  •  0
  •   ArielGM    4 年前

    如果要向firestore添加用户文档,只需将数据“name,photo,address…”添加到pushUserData()方法。

    private pushUserData( user: User ) {
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
    const data: User = {
      uid: user.uid,
      email: user.email,
      displayName: "exampleName",    <-------
      photoUrl: 'https://photo....'  <-------
    };
    userRef.set(data, {merge: true});
    }
    

    现在,如果要设置firebase auth数据的displayName字段,只需在push方法之前更新de firebase user profile。这样地。。。

    emailSignUp(email: string, password: string) {
    return this.afAuth.auth
      .createUserWithEmailAndPassword(email, password)
      .then(credential => {
    
        // ------------- update profile ------------- //
        credential.user.updateProfile({
           displayName: "exampleName",
           photoUrl: "https://photo..."
        })
        // ------------------------------------------ //
    
        this.pushUserData(credential.user);
        console.log('Usuario creado')
        this.router.navigate(['/login'])
      })
      .catch(error => {
        this.handleError(error)
      });
    }
    
    If you do not want to add an User doc to Firestore and just use the Firestore Auth data, you don`t need the pushUserData() method.
    
        4
  •  -1
  •   Bhargav Rao Ankit    4 年前

    你需要添加 私有显示名称:string; 在你的服务.ts