Firebase+Angular环境下Firestore创建文档函数无法工作求助
问题:Firebase Firestore无法创建用户集合并存储数据
问题描述
注册用户后,尝试调用Firestore服务创建Users集合并存储用户数据,但该功能无法正常工作。已更新Firebase配置文件,尝试多种实现方式均未解决。
相关代码
组件中调用Firestore的代码
this.authSvc.register(email, password).then((result) => { this.authSvc.logout(); this.verifyEmail(); this.res = result?.user; this.registerDB(); }) .catch((error) => { this.toastr.error(this.firebaseError.codeError(error.code), 'Error'); this.loading = false; }); verifyEmail() { this.afAuth.currentUser.then(user => user?.sendEmailVerification()) .then(() => { this.toastr.info('Se envio un correo con el link de verificación', 'Verificar Email') this.router.navigate(['/verify-email']) }); } async registerDB() { const path = 'Users'; const id = this.res.uid; this.userData.uid = id; this.userData.password = null; await this.frservice.createDoc(this.userData, path, id); }
Firestore服务代码
import { Injectable } from '@angular/core'; import { AngularFirestore } from '@angular/fire/compat/firestore'; @Injectable({ providedIn: 'root' }) export class FirestoreService { constructor(private firestore: AngularFirestore) { } createDoc(userData: any, path: string, id: string) { const collection = this.firestore.collection(path); return collection.doc(id).set(userData); } getId() { return this.firestore.createId(); } getCollection<tipo>(path: string) { const collection = this.firestore.collection<tipo>(path); return collection.valueChanges(); } getDoc<tipo>(path: string, id: string) { return this.firestore.collection(path).doc<tipo>(id).valueChanges() } }
解决方案
1. 修复异步执行顺序与用户登录状态问题
当前代码在注册成功后立即登出用户,导致后续调用registerDB时处于未认证状态,而Firestore默认安全规则会拒绝未认证用户的写入请求。调整流程顺序,先完成数据写入,再发送验证邮件,最后登出:
this.authSvc.register(email, password).then(async (result) => { this.res = result?.user; // 先写入用户数据 await this.registerDB(); // 传入当前用户对象发送验证邮件,避免依赖已登出的currentUser this.verifyEmail(this.res); // 最后登出 this.authSvc.logout(); }) .catch((error) => { this.toastr.error(this.firebaseError.codeError(error.code), 'Error'); this.loading = false; }); // 修改verifyEmail方法,直接接收用户对象 verifyEmail(user: any) { user.sendEmailVerification() .then(() => { this.toastr.info('Se envio un correo con el link de verificación', 'Verificar Email') this.router.navigate(['/verify-email']) }) .catch(err => console.error('发送验证邮件失败:', err)); }
2. 添加错误捕获排查问题
在registerDB中添加try/catch,捕获写入Firestore时的具体错误,便于定位问题:
async registerDB() { try { const path = 'Users'; const id = this.res.uid; this.userData.uid = id; this.userData.password = null; await this.frservice.createDoc(this.userData, path, id); console.log('用户数据写入Firestore成功'); } catch (error) { console.error('写入Firestore失败:', error); this.toastr.error('存储用户信息失败,请稍后重试', 'Error'); } }
3. 检查Firestore安全规则
确保Firestore规则允许认证用户写入自己的文档,示例规则如下:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /Users/{userId} { // 仅允许认证用户创建/更新自己的文档 allow create, update: if request.auth != null && request.auth.uid == userId; // 允许认证用户读取用户数据(可根据需求调整) allow read: if request.auth != null; } } }
4. 确认userData有效性
检查this.userData是否包含预期的用户信息(如邮箱、用户名等),避免写入空文档或缺失关键数据。
内容的提问来源于stack exchange,提问作者Omar Alejandro Sánchez Cuevas
相关产品推荐
相关产品推荐

