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

使用Angular Fire遇FirebaseError:预期Query类型却得自定义wh对象

问题

参照Angular Fire官方文档的代码示例开发时,浏览器控制台抛出错误:
ERROR FirebaseError: Expected type 'Query', but it was: a custom wh object

组件代码如下:

export class CategoryComponent {

  private fs: Firestore = inject(Firestore);
  categories$: Observable<Category[]>;

  constructor() {
    // 获取categories集合的引用
    const categoryCollection = collection(this.fs, 'categories');

    // 使用collectionData获取集合中的文档数据
    this.categories$ = collectionData(categoryCollection) as Observable<Category[]>;

    console.log(categoryCollection);
  }

}

HTML文件代码如下:

<section>
  <h1>分类</h1>
  <ul>
      <li *ngFor="let item of categories$ |async">
          {{item.category}}
          {{item.log}}
      </li>
  </ul>
</section>
解决方案

出现这个错误的核心原因是Angular Fire与Firebase JS SDK之间的类型不兼容,或者导入/依赖配置有误,以下是具体解决步骤:

  • 对齐版本兼容性:@angular/fire和firebase包的版本必须严格匹配,版本不匹配会导致内部类型冲突。查看Angular Fire的版本说明,确认对应兼容的Firebase版本后,重新安装依赖:

    npm uninstall @angular/fire firebase
    npm install @angular/fire@<对应版本> firebase@<对应版本>
    
  • 统一导入路径:确保所有Firestore相关API都从@angular/fire/firestore导入,禁止混用firebase/firestore的直接导入,否则会导致类型不匹配。正确导入示例:

    import { Firestore, collection, collectionData } from '@angular/fire/firestore';
    import { Observable } from 'rxjs';
    
  • 清理依赖缓存:删除项目根目录下的node_modules文件夹、package-lock.json文件,重新执行npm install,再重启开发服务器,避免缓存导致的类型异常。

  • 检查模块配置:确保组件所在的NgModule中已经导入AngularFirestoreModule并添加到imports数组中,否则Firestore实例无法正确初始化:

    import { AngularFirestoreModule } from '@angular/fire/firestore';
    
    @NgModule({
      imports: [
        // ...其他模块
        AngularFirestoreModule
      ]
    })
    export class YourModule { }
    

内容的提问来源于stack exchange,提问作者Fabio Medeiros

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:53:29