步入数据流并输出过滤数据Rxjs数组

时间:2017-11-10 17:20:17

标签: javascript angular functional-programming rxjs

我有一个数据流,所以我使用了flatMap来打破它。

enter image description here

flatMap开始,我想要一个英雄对象,所以我使用map进入该对象,然后订阅。现在我的问题是,数据单独到达subscribe。如下图所示。

enter image description here

我想在流中收集所有内容,然后输出订阅中所有数据的数组。

这是我的代码。

this.subscription = this.heroService.getAll()
.flatMap(h=>{ console.log("From flatMap",h); return h})
.map((h : any)=>h.hero)
 .subscribe(heroes => {
   console.log("From subscribe",heroes);
 })

我希望订阅看起来像下面的内容。

enter image description here

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用toArray()运算符。

请注意toArray()需要源Observable才能完成。否则它不会发出任何东西。如果您知道它无法完成,您可以使用scan()运算符并自行收集项目。

答案 1 :(得分:1)

如果您想订阅接收英雄数组,请不要使用flatMap。只需使用地图:

this.subscription = this.heroService.getAll()
.map((results:Array<any>) => results.map(r => r.hero))
 .subscribe(heroes => {
   console.log("From subscribe",heroes);
 })