无法通过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官方提供的独立函数操作数据库。
修复步骤:
- 导入所需的Firestore操作函数:
import { collection, doc, valueChanges } from '@angular/fire/firestore'; import { switchMap } from 'rxjs/operators'; // 优化订阅嵌套时需要
- 修改
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
相关产品推荐
相关产品推荐

