Return nested collection from firestore as object for angularfire2 and firebase

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-18 12:47:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!