【问题标题】:Loop through angularfire2 list循环遍历 angularfire2 列表
【发布时间】:2017-03-02 16:55:12
【问题描述】:

假设我需要从项目订单中获取所有项目。

  • 我需要从订单中获取商品密钥
  • 遍历每个项目键并订阅每个.database.object 以获取项目详细信息。

 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);
     });

   });
 });

这可能会有问题,因为orderItems 订阅尚未完成,forEach 已执行。当然我可以稍后检查列表是否重复,但我很确定有更好的方法。

我的问题 - 有没有更好的方法来做到这一点?

【问题讨论】:

    标签: firebase firebase-realtime-database reactive-programming rxjs angularfire2


    【解决方案1】:

    我认为您可以通过指定 preserveSnapshot 选项来获取原始快照的数据,如下所述: Retrieving the snapshot 然后根据需要进行迭代。

    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);
        });
      });
    })
    

    我认为您也可以立即将带有键的items 映射到order_items,如下所示:AngularFire for Angular 2,但我不确定如何执行此操作,因为我是 ng2、af2 和火力基地。

    【讨论】:

    • 不确定preserveSnapshot 做了什么,但问题仍然存在 - 这与它无关。我认为这个问题的出现是因为可观察流不好。
    猜你喜欢
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2013-09-04
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多