使用AngularFire调用Firestore getCountFromServer()时遇TypeError错误求助
解决AngularFire中使用getCountFromServer()的类型不兼容错误
问题原因
你当前混合使用了AngularFire的兼容版(compat)API与Firebase v9模块化API,导致类型不匹配:
- 从
@angular/fire/compat/firestore导入的AngularFirestore,其.collection(...).ref返回的是Firebase v8版本的CollectionReference - 而
getCountFromServer()是Firebase v9模块化API,要求传入v9版本的CollectionReference,两者不兼容引发内部属性读取错误(即报错中的Cannot read properties of undefined (reading 'wt'))
解决方案
方案1:使用AngularFire模块化API(推荐)
直接使用AngularFire提供的模块化API,获取符合要求的v9集合引用:
import { Component, OnInit } from '@angular/core'; import { AngularFireFirestore, collection } from '@angular/fire/firestore'; import { getCountFromServer } from '@angular/fire/firestore'; @Component({ selector: 'test-member-size', templateUrl: './test-member-size.component.html', }) export class TestMemberSizeComponent implements OnInit { constructor(private firestore: AngularFireFirestore) { } async ngOnInit() { // 创建v9版本的集合引用 const collRef = collection(this.firestore, 'organizations/abc-org/members'); const countSnapshot = await getCountFromServer(collRef); console.log('成员数量:', countSnapshot.data().count); } }
方案2:兼容现有compat代码
如果需要继续使用兼容版的AngularFirestore,可以通过其.firestore属性获取v9的Firestore实例,再创建对应集合引用:
import { Component, OnInit } from '@angular/core'; import { AngularFirestore } from '@angular/fire/compat/firestore'; import { getCountFromServer, collection } from '@angular/fire/firestore'; @Component({ selector: 'test-member-size', templateUrl: './test-member-size.component.html', }) export class TestMemberSizeComponent implements OnInit { constructor(private firestore: AngularFirestore) { } async ngOnInit() { // 获取v9版本的Firestore实例 const firestoreV9 = this.firestore.firestore; // 创建v9版本的集合引用 const collRef = collection(firestoreV9, 'organizations/abc-org/members'); const countSnapshot = await getCountFromServer(collRef); console.log('成员数量:', countSnapshot.data().count); } }
内容的提问来源于stack exchange,提问作者trustkool
相关产品推荐
相关产品推荐

