建议将Firestore的doc模块替换为document及相关问题咨询
Firebase 9命名建议与别名解决方案
背景
我偏好Firebase 9的模块化设计,但认为doc这个命名不够统一——collection用的是完整名称而非缩写col,doc也应该改成document,同时deleteDoc对应改成deleteDocument,这样能避免变量名冲突的问题。
比如这段代码因为参数名doc和导入的doc重名,直接报错无法运行:
import { doc, collection, deleteDoc } from '@angular/fire/firestore'; this.querySnapshot.forEach((doc) => { deleteDoc(doc(this.firestore, 'users', doc.id)); });
不得不改成这样规避冲突:
import { doc, collection, deleteDoc } from '@angular/fire/firestore'; this.querySnapshot.forEach((docElement) => { deleteDoc(doc(this.firestore, 'users', docElement.id)); });
而理想的写法应该是这样:
import { document, collection, deleteDocument } from '@angular/fire/firestore'; this.querySnapshot.forEach((doc) => { deleteDocument(document(this.firestore, 'users', doc.id)); });
问题解答
1. 如何向Firebase团队提交命名修改请求?
- 前往Firebase Firestore的官方GitHub仓库提交Issue,清晰描述命名不一致的问题:指出
collection使用完整名称,而doc/deleteDoc用缩写,导致的变量冲突困扰,建议将doc改为document、deleteDoc改为deleteDocument以保持命名风格统一。 - 也可以通过Firebase控制台内的反馈入口提交建议,描述同样的内容。
2. 如何为doc创建别名?
你之前的写法出错是因为forEach普通函数回调里的document会优先指向浏览器全局的document对象,而非类的实例属性。推荐两种正确的方式:
方式一:导入时直接重命名(最简便)
在导入阶段就给目标方法设置别名,直接使用即可:
import { doc as document, collection, deleteDoc as deleteDocument } from '@angular/fire/firestore'; this.querySnapshot.forEach((doc) => { deleteDocument(document(this.firestore, 'users', doc.id)); });
方式二:类内定义别名并正确访问
如果要在类内维护别名,需要注意this的指向问题,用箭头函数或者提前保存this引用:
import { doc, collection, deleteDoc } from '@angular/fire/firestore'; export class AppComponent { private document = doc; handleDelete() { // 方法1:保存this引用 const self = this; this.querySnapshot.forEach((doc) => { deleteDoc(self.document(this.firestore, 'users', doc.id)); }); // 方法2:使用箭头函数(自动绑定类的this) this.querySnapshot.forEach((doc) => { deleteDoc(this.document(this.firestore, 'users', doc.id)); }); } }
内容的提问来源于stack exchange,提问作者Thomas David Kehoe
相关产品推荐
相关产品推荐

