首页 > 解决方案 > 当我订阅我的服务方法(执行查询)时,如何检索从 FireStore DB 检索到的每个文档的 UID?

问题描述

我正在开发一个从 Firebase FireStore数据库中检索数据的 Angular 项目。它工作正常,但现在我在尝试检索文档 UID 时发现问题。我将尝试详细解释我的情况。

在我的 FireStore 数据库中,我有这样的东西:

在此处输入图像描述

因此,正如您所看到的,目前我只有一个名为calendar的集合,其中包含一些文档,其中每个文档代表日历上的一个事件(但现在这个细节并不那么重要)。

在我的 Angular 应用程序中,我有一个包含此方法的服务类,该方法只需执行查询以检索我的日历集合中的所有文档:

/**
* Return the list of all the work shift related to all the person in the calendar:
*/
getEvents(): Observable<any[]> {
    this.items = this.db.collection('calendar').valueChanges();

    return this.items;
}

所以这个方法在任何对象上返回一个Observable数组。

将此Observable订阅到我的组件中,我检索了存储在 FireStore 中的日历集合中的文档列表。

我已经这样做了(这是我的组件打字稿文件中调用先前服务方法的代码片段):

this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {

  //console.log("START: ", event.start);
  var date = event.start.toDate()
  var hour = date.getHours();

  var startDateAsString = this.fromDateToString(date);

  event.start = startDateAsString;

  if(hour === 7) {
    event['backgroundColor'] = 'red';
  }
  else if(hour === 15) {
    event['backgroundColor'] = 'green';
  }
  else if(hour === 23) {
    event['backgroundColor'] = 'black';
  }

  console.log("EVENT: ", event);

  return event;
})});

如您所见,我正在订阅执行查询的前一个服务方法,并且我使用map()运算符构建我的this.events数组对查询结果集进行“迭代”。它工作正常。

我的问题是:在这种情况下,如何检索 Firebase 检索到的每个文档的 UID,以便将此信息添加到返回的事件变量中?

标签: javascriptangularfirebasegoogle-cloud-firestoreangularfire2

解决方案


valueChanges()不包括id它收到的文件。您需要使用snapshotChanges()然后通过管道传输数据来创建对象。

我在我的应用程序中做这样的事情

this.db.collection('collectionName').snapshotChanges().pipe(
    map(snapshots => {
       return snapshots.map(s => {
        // if you log s here, you can look through the object
        // payload.doc.data() should be the same as what valueChanges returns
        // payload.doc.id will be the id
        // merge them into a new object
        return {...s.payload.doc.data(), id: s.payload.doc.id)}
     })
    }
);

推荐阅读