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

Angular 6中如何将Firebase Auth生成的UID插入数据库对象?

问题:将Firebase Auth用户UID插入Database对象中

我来帮你搞定这个问题!你已经离目标很近了,只需要在调用save方法前,把Firebase Auth返回的UID赋值给user对象的id属性就可以了。

先看看你现有的代码:

auth.ts 现有用户创建逻辑

createUser(user: any, path: string) { 
  return this.afu.auth.createUserWithEmailAndPassword(user.email, user.password) 
    .then((res) => { 
      let id = res.uid; 
      this.teste(id, path); 
      return this.service.save(user, path); 
    }); 
}

userService.ts 现有save方法

save(user: any, path: string) { 
  return new Promise((resolve, reject) => { 
    return this.db.list(this.PATH + path) 
      .push(user) 
      .then(() => resolve()) 
  }) 
}

解决方案

这里有两种可行的实现方式,你可以根据需求选择:

方式1:不修改原始user对象(推荐)

如果担心修改原始user对象会影响其他业务逻辑,可以用扩展运算符创建一个包含UID的新对象,再传入save方法:

createUser(user: any, path: string) { 
  return this.afu.auth.createUserWithEmailAndPassword(user.email, user.password) 
    .then((res) => { 
      const userId = res.uid; 
      this.teste(userId, path); 
      // 生成带UID的新用户对象,保留原对象所有属性并添加id字段
      const userWithId = { ...user, id: userId };
      // 将新对象传入save方法
      return this.service.save(userWithId, path); 
    }); 
}

方式2:直接修改原始user对象

如果确定修改原始对象不会有问题,也可以直接给原user添加id属性:

createUser(user: any, path: string) { 
  return this.afu.auth.createUserWithEmailAndPassword(user.email, user.password) 
    .then((res) => { 
      user.id = res.uid; // 直接给原user对象添加id属性
      this.teste(user.id, path); 
      return this.service.save(user, path); 
    }); 
}

两种方式都能让save方法把包含UID的对象存入Firebase Database,你可以根据自己的代码场景选择合适的方案。

内容的提问来源于stack exchange,提问作者Rafael Moura

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:27:48