简体   繁体   English

如何从AngularFire2的2级下移键控列表中获取平坦的可观察列表

[英]How to get flat observable list from 2 level down keyed list in AngularFire2

I can't figure out how to get flat collection of Products where I've managed my data in form Prods/$companyKeys/$prodKeys 我无法弄清楚如何以产品Prods / $ companyKeys / $ prodKeys的形式管理产品的统一集合

{
  "ID1" : {
    "prodID1" : {
      "name" : "Car"
    },
    "prodID2" : {
      "name" : "Door"
    },
    "prodID3" : {
      "name" : "Sandwich"
    }
  },
  "ID2" : {
    "ProdID4" : {
      "name" : "Glass"
    },
    "ProdID5" : {
      "name" : "Pen"
    }
  }
}

Is there a simple way in rxjs or in AngularFire2 itself to get directly collection of products, omitting company Ids? 在rxjs或AngularFire2本身中,有没有一种简单的方法可以直接收集产品而忽略公司ID? Or do I have to re-arrange my data? 还是我必须重新安排我的数据?

Thanks 谢谢

Observable.flatMap is made for such a purpose ( fiddle ): 为此创建Observable.flatMap小提琴 ):

// turn products into array
var arr = [];
for(var key in products) {
  arr.push(products[key]);
}

Rx.Observable.from(arr)
  .flatMap(x => {
    // 'x' is like object ID1, create array of products
    var arr = [];
    for (var key in x) {
      arr.push(x[key]);
    }
    return Rx.Observable.from(arr);
  })
  .subscribe(x => document.write(JSON.stringify(x) + '</br>'));

Output: 输出:

{"name":"Car"}
{"name":"Door"}
{"name":"Glass"}
{"name":"Sandwich"}
{"name":"Pen"}

Not sure how you want to handle the keys, but you can use Observable.pairs to make it even easier to loop through the object properties. 不确定如何处理键,但是可以使用Observable.pairs使其更容易遍历对象属性。 The resulting stream is of arrays with the first element being the key and the second being the value for the object properties: 结果流是数组,第一个元素是键,第二个元素是对象属性的值:

Rx.Observable.pairs(products)
    .flatMap(x => Rx.Observable.pairs(x[1]))
    .subscribe( x => console.log(x[0], x[1]));

This returns arrays like this: 这将返回如下数组:

["prodID1", {name: "Car"}]
["prodID2", {name: "Door"}]
["prodID3", {name: "Glass"}]
["prodID4", {name: "Sandwich"}]
["prodID5", {name: "Pen"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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