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

How can I retrieve the UID of each document retrieved from FireStore DB when I subscribe my service method (performing the query)?

我正在开展一个 Angular 项目,从 Firebase FireStore 数据库检索数据。它工作正常,但现在我在尝试检索文档 UID 时发现问题。我会尽量详细说明我的情况。

进入我的 FireStore DB 我有这样的东西:

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

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

/**
* 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;
}

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

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

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

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() 运算符构建我的 [=33] 在查询结果集上“迭代” =]this.events数组。它工作正常。

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

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)}
     })
    }
);