angular - 仅从一个已知子集合中检索所有文档
问题描述
我有这个 Firestore 结构:
Category: {
document1a: {
name : "reptiles"
animalsubcollection: {
Document1b: {
name: "snake"
color: "white"
}
Document2b: {
name: "lizard"
color: "black"
}
document2a: {
name : "mammals"
animalsubcollection: {
Document1b: {
name: "monkey"
color: "brown"
}
Document2b: {
name: "cat"
color: "white"
}
我需要在一个页面中列出该信息,按如下类别分类:
爬行动物:
- 蛇:白色
- 蜥蜴:黑色
哺乳动物:
- 猴子:棕色
- 猫:白色
像上面的例子一样,我总是只有一个已知的子集合,称为animalsubcollection
.
我如何在 Angular 5 中使用 AngularFire2 来实现这一点?
如果它不是此类信息的最佳 Firestore 模型,我可以在必要时更改它。我接受其他人的建议以达到相同的结果。
解决方案
感谢大家的建议,但最初的建议不是对原始数据库模型进行规范化,而是使用原始模型找到一个简单的解决方案。
我知道有时候,只需简单地创建 2 或 3 个新的规范化集合并解决问题就更容易了。另一方面,如果有可能创建子集合,则需要存在一种以 Angular em RxJS 方式查询其数据的方法。
因此,经过 2 或 3 天的研究,我找到了一种方法:
//necessary imports
import { Observable } from 'rxjs/observable';
import { combineLatest } from 'rxjs/observable/combineLatest';
import 'rxjs/add/operator/mergeMap';
// the observable for animals category collection
this.animals = this.afs
.collection('Category')
.snapshotChanges()
.map(arr => {
return arr.map(snap => {
const categ = { id: snap.payload.doc.id, ...snap.payload.doc.data() };
// the animalsubcollection, using the previous value as parameter
return this.afs
.collection(`Category/${categ.id}/animalsubcollection`)
.valueChanges()
.map(animalsub => {
return { ...categ, animalSubs: animalsub };
});
});
})
.mergeMap(result => combineLatest(result));
//thats the trick. Combine 2 observables into a new one.
在视图中:
<ion-card *ngFor="let animal of animals | async">
<p *ngFor="let as of animal.animalSubs">
{{as.name}} - {{as.color}}
</p>
我希望它可以帮助某人
推荐阅读
- reactjs - 失败的道具类型:组件:道具类型`props`无效;
- sql - 半联接与子查询
- delphi - Delphi VCL - WM_Touch RegisterTouchWindow(Handle, 0); 触摸面板时不会处理消息
- android - Fragment BackStack 生命周期问题
- linux - Ghostscript:如何包含它曾经包含的 Apple ImageWriter 驱动程序?
- google-apps-script - 使用 Google Sheets Apps 脚本创建发送数据的日志选项卡
- javascript - 尝试制作矩形是否有什么问题?
- nginx - 使用 ngx.ctx 在 Openresty/Lua 中的块之间传递变量
- html - 如何使图像垂直溢出div?
- python - 如何在保持宽度相同的同时强制子图的纵横比?