简体   繁体   中英

Return nested collection from firestore as object for angularfire2 and firebase

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM