javascript - 当我订阅我的服务方法(执行查询)时,如何检索从 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,以便将此信息添加到返回的事件变量中?
解决方案
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)}
})
}
);
推荐阅读
- async-await - karma-typescript:使用 Async 关键字导入 JS 文件
- java - SQLite 数据库游标初始化异常
- powershell - Powershell 递归搜索以选择 .txt 文件,然后将所有文件的内容输出到单个 .txt 文件中
- python - Discord.py 机器人无法 ping,有人可以告诉我该怎么做吗?
- image - 使用单应矩阵并将其分解以找到固定在中心的平面的方向
- mysql - 参数 2 中的 JSON 文本无效 - 使用 Spring JPA 的 json_contains
- python - div中的Beautifulsoup打印值
- javascript - 我在自动刷新网页内容时遇到问题
- kotlin - CoroutineScope 背后的概念是什么?
- docker - 如何使用 openshift source-to-image 库而不是 s2i 二进制或可执行文件