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

如何在AngularFire 7+(Firebase 9)中获取类型化对象

解决方案

要在AngularFire模块化方案中正确类型化从Firestore获取的文档Observable,你可以通过以下步骤实现:

完整代码示例

import { Firestore, doc, docData } from '@angular/fire/firestore';
import { Auth } from '@angular/fire/auth';
import { Observable, of } from 'rxjs';

// 假设你的Queue接口定义如下
interface Queue {
  // 替换为你的实际字段
  items: string[];
  createdAt: Date;
}

@Component({
  // 组件元数据(如selector、templateUrl等)
})
export class YourComponent {
  public readonly myQueue$: Observable<Queue | null>;

  constructor(private firestore: Firestore, private auth: Auth) {
    const userId = this.auth.currentUser?.uid;
    
    if (!userId) {
      // 用户未登录时返回null的Observable
      this.myQueue$ = of(null);
      return;
    }

    // 创建带类型的文档引用
    const docReference = doc<Queue>(this.firestore, `queues/${userId}`);
    // 获取带类型的文档数据Observable
    this.myQueue$ = docData<Queue | null>(docReference);
  }
}

关键说明

  • 处理用户未登录场景:auth.currentUser可能为null,必须先校验userId是否存在,避免生成无效的文档引用,同时保证Observable的类型始终是Queue | null。
  • 泛型的正确使用:
    • doc<Queue>(...)会创建DocumentReference<Queue>类型的引用,明确指定该文档的结构为Queue。
    • docData<Queue | null>(...)直接指定返回的Observable类型,确保和你定义的myQueue$类型完全匹配。
  • 可选:包含文档ID:如果需要将文档ID一并返回,可以在docData中添加配置,同时更新Queue接口:
    // 更新Queue接口
    interface Queue {
      id: string;
      items: string[];
      createdAt: Date;
    }
    
    // 获取包含ID的文档数据
    this.myQueue$ = docData<Queue | null>(docReference, { idField: 'id' });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:45:31