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

AngularFire2中无法获取x.payload.exists,如何检查Firestore文档是否存在?

解决AngularFire2中判断Firestore文档是否存在的问题

看起来你遇到的问题是在使用snapshotChanges()时找不到exists属性——这大概率是对AngularFire返回结构的理解偏差,或者版本适配的小问题。我给你两种可行的解决方案:

方案一:修正snapshotChanges()的使用方式

snapshotChanges()返回的是Observable<Action<DocumentSnapshot<T>>>,其中action.payload就是Firebase的DocumentSnapshot对象,它的exists是一个getter属性,控制台打印时可能不会直接显示,但实际可以正常访问。调整代码如下:

this.angularFirestore.doc(`users/${credentials.user.uid}`)
  .snapshotChanges()
  .subscribe(action => {
    // 直接访问exists判断文档是否存在
    const isDocExists = action.payload.exists;
    
    if (isDocExists) {
      // 文档存在的逻辑
      const userData = action.payload.data();
      console.log("用户文档存在,数据:", userData);
    } else {
      // 文档不存在的逻辑
      console.log("用户文档不存在");
    }
  });

如果TypeScript提示找不到exists,可以尝试添加类型断言:(action.payload as firebase.firestore.DocumentSnapshot).exists。

方案二:改用get()方法(更简洁)

如果你不需要监听文档的实时变化,只是一次性判断是否存在,get()方法会更直观——它直接返回Observable<DocumentSnapshot<T>>:

this.angularFirestore.doc(`users/${credentials.user.uid}`)
  .get()
  .subscribe(docSnapshot => {
    if (docSnapshot.exists) {
      // 文档存在的逻辑
      const userData = docSnapshot.data();
      console.log("用户数据:", userData);
    } else {
      // 文档不存在的逻辑
      console.log("未找到该用户的文档");
    }
  });

这个方法适合不需要实时同步的场景,代码结构也更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:42:43