首页 > 解决方案 > 获取 doc.id 作为响应以及集合中的数据

问题描述

从集合中获取数据leads并显示 Html 表上的所有文档。单击时,我需要获取单击项目的 doc.id,因为它是唯一的主键

PS我正在获取数组中所有文档的记录。我也需要在同一个数组中的文档 ID。

下面是我用来获取数据的代码。我正在推动tableData阵列。我想要这个数组中的 docid。

 this.firestore.collection('leads' , ref => ref 
.limit(5)
).snapshotChanges()
.subscribe(response => {
if(!response.length){
  console.log("no data available");
  return false;
}
this.firstInResponse = response[0].payload.doc;
this.lastInResponse = response[response.length - 1].payload.doc;


this.tableData = [];
for(let item of response){
  this.tableData.push(item.payload.doc.data()); 
  console.log(this.tableData);
}

...

为了清楚起见,附上 console.log 和 Firestore 的屏幕截图。

在此处输入图像描述

编辑 1

在尝试这个之后

for(let item of response){
  var data = item;
  Object.assign(data, {id : item.payload.doc.id})
  this.tableData.push(data);
  console.log(this.tableData);

我的实际数组坏了,下面是截图

在此处输入图像描述

标签: angulartypescriptfirebasegoogle-cloud-firestore

解决方案


尝试这个,

for(let item of response){
 var data = Object.assign(item.payload.doc.data(), {id : item.payload.doc.id})
 this.tableData.push(data);
 console.log(this.tableData);
}

我从中获取了 id item.payload.doc.id,然后将 id 属性添加到数据对象,然后将修改后的对象推送到 tableData

希望这可以帮助!!


推荐阅读