问题
Let's say you have the following structure:
shopping-carts (collection)
- shopping-cart 1(doc)
-- dateCreated (field)
-- items (collection)
- shopping-cart 2(doc
-- dateCreated
-- items
.
.
.
So, how would we go about getting the entire shopping-cart(doc) as an ShoppingCart object that we defined as
export interface ShoppingCart {
items: ShoppingCartItem[]
dateCreated: string
}
afs.doc('shopping-cart/id').valueChanges()
only returns the dateCreated
afs.doc('shopping-cart/id').collection('items').valueChanges()
returns the items.
Easy way to get all in one and create it as an object?
回答1:
Probably not the best solution, but couldn't find a better one yet.
this.shoppingCartsCollection = afs.collection<Servicio>('shopping-carts',
ref => ref.orderBy('dateCreated', 'asc'));
this.shoppingCarts = this.shoppingCartsCollection
.snapshotChanges()
.map(values => {
return values.map(value => {
const shopping-cart = value.payload.doc.data();
const itemsArray = shopping-cart.items;
shopping-cart.observableItems = [];
for (var i = 0, len = itemsArray.length; i < len; i++) {
itemDocRef = itemsArray[i];
value.observableItems.push(afs.doc('items/'+ itemDocRef.id).valueChanges());
}
return shopping-cart;
});
});
access your items data, like any other observable
<div *ngFor="let shoppingCart of shoppingCarts | async">
<p *ngFor="let observableItem of shoppingCart.observableItems">
{{(observableItem | async)?.displayName}}
</p>
</div>
来源:https://stackoverflow.com/questions/46865124/return-nested-collection-from-firestore-as-object-for-angularfire2-and-firebase