Angular Fire 7.5.0命名Firestore数据库聚合查询报错求助
解决Angular Fire 7.5.0中命名Firestore数据库的聚合查询报错问题
问题分析
使用命名Firestore数据库时,普通集合查询可正常工作,但调用getCountFromServer做聚合统计时返回INVALID_ARGUMENT错误,提示缺少x-goog-request-params请求头。这是因为Angular Fire 7.5.0在处理聚合查询时,未自动将命名数据库的ID注入请求头,而普通查询的请求头处理逻辑不同,因此不受影响。
解决方案
方案1:升级Angular Fire版本
Angular Fire在7.6.0及以上版本修复了命名数据库聚合查询的请求头问题,直接升级依赖即可:
npm install @angular/fire@latest firebase@latest
升级后重新构建项目,聚合查询就能正常使用命名数据库。
方案2:手动配置Firestore实例请求头(适合无法升级版本的场景)
如果无法升级版本,可手动初始化Firestore实例并添加请求头拦截:
- 修改AppModule中的
provideFirestore配置:
import { provideFirestore, Firestore } from '@angular/fire/firestore'; import { initializeApp } from 'firebase/app'; import { getFirestore, FirestoreSettings } from 'firebase/firestore'; import { environment } from '../environments/environment'; const firestoreSettings: FirestoreSettings = { headers: { 'x-goog-request-params': `project_id=${environment.firebase.projectId}&database_id=test` } }; export const appConfig = { providers: [ provideFirebaseApp(() => initializeApp(environment.firebase)), provideAuth(() => getAuth()), provideFirestore(() => { const firestore = getFirestore('test'); firestore.settings(firestoreSettings); return firestore; }) ] };
确保environment.firebase包含projectId字段,或直接替换为你的项目ID字符串。
- 重新运行项目,此时
getCountFromServer请求会自动带上所需请求头,问题即可解决。
验证
执行以下聚合查询代码,应能正常返回文档数量:
private firestore: Firestore = inject(Firestore); private collectionName = environment.firestoreCollections.example; async getDocumentCount(): Promise<number> { const c = collection(this.firestore, this.collectionName); const snapshot = await getCountFromServer(c); return snapshot.data().count; }
内容的提问来源于stack exchange,提问作者Jose Valentin Abundo Hernandez
相关产品推荐
相关产品推荐

