添加自定义 variable/data 到 AngularFirestoreDocument

Add custom variable/data to AngularFirestoreDocument

我有这样的代码来登录用户并将其保存到 firebase 数据库

async EmailRegister(email: any, password: any, displayName: any) {
  return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((result) => {
      result.user.updateProfile({
        displayName: displayName,
        photoURL: ''
      }).then(() => {
        this.updateUserData(result.user);
        // this.SendVerificationMail();
        this.router.navigateByUrl('/pages/projects/all-project');
        window.alert("You have been successfully registered!");
        console.log(result.user)
      });
    }).catch((error) => {
      window.alert(error.message)
    })
}

private updateUserData(user) {
  // Sets user data to firestore on login
  const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
  const data = {
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL,
    emailVerified: user.emailVerified,
    kewirusType: user.kewirusType
  }
  return userRef.set(data, { merge: true })
}

我想在用户注册时传递 kewirusType 等新数据,该怎么做?

要解决您的问题,请尝试将 kewirusType 从表单传递给 updateUserData 例如:

  1. 将 kewirus 传递给此方法:
async EmailRegister(email: any, password: any, displayName: any, kewirusType: string) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((result) => {
    result.user.updateProfile({
        displayName: displayName,
        photoURL: ''
      }).then(() => {
        this.updateUserData(result.user, kewirusType);
        // this.SendVerificationMail();
        this.router.navigateByUrl('/pages/projects/all-project');
        window.alert("You have been successfully registered!");
        console.log(result.user)
      });
    }).catch((error) => {
    window.alert(error.message)
    })
}
  1. updateUserData:
private updateUserData(user, kewirusType: string) {
// Sets user data to firestore on login
  const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
  const data = {
uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL,
    emailVerified: user.emailVerified,
    kewirusType //notice change here
  }
  return userRef.set(data, { merge: true })
}

额外:

考虑使用 firebase functions 创建 user/{uuid} 文档,而不是在您的应用中创建此数据,例如:


export const initUserData = functions.auth.user().onCreate((user) => {
  const collectionDoc = admin.firestore().collection(`users`);

  return collectionDoc.doc(user.uid).set({
    uid: user.uid,
    email: user.email,
    kewirusType: "value"
    //... your data here
  }).then(() => {
    console.log(`Data for user ${user.uid} initialized`);
  });

});

然后在您的应用中,您只需订阅 /user/{uuid} 文档即可获取用户数据。将此类流程委托到应用程序外部会更好、更安全。

Firebase 函数可以访问每个 firebase 服务(身份验证、文档、存储等),所以基本上您可以用它做很多事情。