You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 14 + FireStore注册时添加isAdmin自定义字段?

解决方案

Firebase Auth 的内置用户对象不支持直接添加自定义字段(比如你需要的 isAdmin),所以我们得把这类自定义用户数据存在 Firestore 里,和 Auth 创建的用户绑定起来。

你可以按下面的方式修改 saveUser 方法:

  1. 给方法添加 isAdmin 参数,接收复选框的布尔值
  2. 在创建用户、更新 Auth 资料后,把完整的用户数据(包括 isAdmin)写入 Firestore 的 users 集合,用用户的 UID 作为文档 ID(确保一一对应)

修改后的代码如下:

import { doc, setDoc } from '@angular/fire/firestore';
// 确保已经注入 Auth 和 Firestore 实例
constructor(private auth: Auth, private firestore: Firestore) {}

saveUser(firstName: any, lastName: any, email: any, password: any, isAdmin: boolean) {
  return from(createUserWithEmailAndPassword(this.auth, email, password)).pipe(
    switchMap(({ user }) => {
      // 先更新 Auth 用户的显示名称
      return updateProfile(user, { displayName: `${firstName} ${lastName}` }).pipe(
        // 再将用户数据写入 Firestore
        switchMap(() => {
          const userDocRef = doc(this.firestore, `users/${user.uid}`);
          return setDoc(userDocRef, {
            uid: user.uid,
            firstName,
            lastName,
            email,
            isAdmin: isAdmin || false // 默认设为 false,防止未传值的情况
          });
        })
      );
    })
  );
}

调用方法时注意

在处理注册表单提交时,把复选框的状态(布尔值)传给 saveUser 方法就行,比如用响应式表单的话:

// 假设你的表单有 isAdmin 控件
this.saveUser(
  this.registerForm.value.firstName,
  this.registerForm.value.lastName,
  this.registerForm.value.email,
  this.registerForm.value.password,
  this.registerForm.value.isAdmin
).subscribe({
  next: () => console.log('用户注册并保存成功'),
  error: (err) => console.error('注册失败', err)
});

这样,每次新用户注册时,isAdmin 字段就会和其他用户信息一起存在 Firestore 里了。

内容的提问来源于stack exchange,提问作者Wahéb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:57:41