TheUnreal
TheUnreal

Reputation: 24492

Loop through angularfire2 list

Assuming I need to get all items from an order of items.


 let myItems = [];
 let orderItems = this.af.database.list('/order_items');

 this.orderItems.subscribe((itemKeys) => {
   itemKeys.forEach((itemKey) => {
     let item = this.af.database.object('/items/'itemKey.$value);

     item.subscribe((itemData) => {
       myItems.push(itemData);
     });

   });
 });

This can be problematic since the orderItems subscription is not yet finished and the forEach is executed. Ofcourse I can check the list for duplicated later, but I'm pretty sure there is better way.

My question - Is there any better way to do this?

Upvotes: 2

Views: 2896

Answers (1)

j809809jkdljfja
j809809jkdljfja

Reputation: 807

I think you can get the data as the original snapshot by specifying the preserveSnapshot option as described here: Retrieving the snapshot and then iterate as you need.

let myItems = [];
let orderItems = this.af.database.list('/order_items',
  { preserveSnapshot: true }
);

this.orderItems.subscribe((itemKeys) => {
  itemKeys.forEach((itemKey) => {
    let item = this.af.database.object('/items/'+itemKey.key);

    item.subscribe((itemData) => {
      myItems.push(itemData);
    });
  });
})

I think you could also map the items with the keys to order_items right away, something like here: AngularFire for Angular 2, but I am not sure how to do this, since I am new to ng2, af2 and firebase.

Upvotes: 2

Related Questions