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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:11:17