首页 > 解决方案 > 如何从 firebase.firestore.DocumentSnapshot 获取文档数据?

问题描述

我从 Firestore 获得文件,它的工作:

this.sub = this.beluginService.getBeluginById(this.personId)
.subscribe((documentSnapshot: firebase.firestore.DocumentSnapshot) => {
  console.log(documentSnapshot.data());
}

我的服务:

  getBeluginById(id: string) {
    return this.afs.collection('belugin').doc(id).get();
  }

在 console.log 我得到一个对象:

{ id: "ya1jibU2pZx1niGiuAmp"
  qwCF: [0, 0, 2, 0, 0, 6, 2]
  qwCO: [0, 0, 0, 0, 2, 0, 0]
  qwIMP: [10, 0, 2, 2, 2, 4, 0]
  qwME: [0, 4, 0, 4, 2, 0, 0]
  qwPL: [0, 0, 0, 0, 0, 0, 0]
  qwRI: [0, 2, 2, 2, 2, 0, 0]
  qwSH: [0, 0, 0, 0, 0, 0, 0]
  qwTW: [0, 4, 4, 2, 2, 0, 8] }

但是当我尝试获取对象属性(等 id、qwCF)时:

this.sub = this.beluginService.getBeluginById(this.personId)
.subscribe((documentSnapshot: firebase.firestore.DocumentSnapshot) => {
  this.id = documentSnapshot.data().id;
  this.qwCF = documentSnapshot.data().qwCF;
}

我无法获取 data() 属性...。我的 VCCode 显示方法 data() 调用错误。为什么?

标签: angularfirebasegoogle-cloud-firestore

解决方案


如果documentSnapshot.data()在日志中工作可能会从其中收集数据会更好:

const data = documentSnapshot.data();
this.id = data.id

可能取决于 ECMA 版本

this.id = data["id"];

推荐阅读