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

无法通过ID从Firebase加载游戏:Firestore无collection属性错误

问题

我配置了Angular路由,通过游戏ID从Firebase加载对应游戏数据:

const routes: Routes = [
  { path: '', component: StartScreenComponent },
  { path: 'game/:id', component: GameComponent }
];

但在GameComponent中编写加载代码时出现错误,组件代码如下:

export class GameComponent implements OnInit {
  pickCardAnimation = false;
  currentCard: string = '';
  game: Game;

  constructor(@Inject(Firestore) private firestore: Firestore, private route: ActivatedRoute, public dialog: MatDialog) {
  }

  ngOnInit(): void {
    this.newGame();
    this.route.params.subscribe((params) => {
      console.log('id:', params['id']);  // Access 'id' using bracket notation

      this
        .firestore
        .collection('games')
        .doc(params['id'])
        .valueChanges()
        .subscribe((game) => {
          console.log('game update', game);
        });
    })
  }

  async newGame() {
    this.game = new Game();
  }
}

错误信息:

Error: src/app/game/game.component.ts:28:10 - error TS2339: Property 'collection' does not exist on type 'Firestore'.
28 .collection('games')

解决方案

错误原因是使用了Firebase 9及以上的模块化版本,该版本中Firestore实例不再直接提供collection方法,需使用Firebase官方提供的独立函数操作数据库。

修复步骤:

  1. 导入所需的Firestore操作函数:
import { collection, doc, valueChanges } from '@angular/fire/firestore';
import { switchMap } from 'rxjs/operators'; // 优化订阅嵌套时需要
  1. 修改ngOnInit中的数据加载代码:

基础修复版本

ngOnInit(): void {
  this.newGame();
  this.route.params.subscribe((params) => {
    console.log('id:', params['id']);
    // 先获取games集合引用,再获取对应ID的文档引用
    const gameCollection = collection(this.firestore, 'games');
    const gameDocRef = doc(gameCollection, params['id']);
    // 监听文档变化
    valueChanges(gameDocRef).subscribe((game) => {
      console.log('game update', game);
      // 将获取到的游戏数据赋值给组件属性,添加类型断言
      this.game = game as Game;
    });
  })
}

优化版本(避免嵌套订阅)

使用switchMap操作符优化RxJS订阅逻辑,避免嵌套订阅带来的潜在内存泄漏问题:

ngOnInit(): void {
  this.newGame();
  this.route.params.pipe(
    switchMap(params => {
      console.log('id:', params['id']);
      const gameCollection = collection(this.firestore, 'games');
      const gameDocRef = doc(gameCollection, params['id']);
      return valueChanges(gameDocRef);
    })
  ).subscribe((game) => {
    console.log('game update', game);
    this.game = game as Game;
  });
}

说明

Firebase 9+采用模块化架构,所有数据库操作都需通过导入对应函数实现,这种设计可按需导入代码,有效减小应用打包体积,同时保持API灵活性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:03:31