2017-12-03 158 views
1

我目前正在努力弄清楚Angular 4应用程序中Rxjs的行为。订阅在当时发出一个项目而不是在Rxjs中的列表

我的代码是:

this.server.get("incidents") //http get resource 
.flatMap((res) => res.value) //the incident array is in a property called value of the json returned 
.map((incident) => new Incident(incident)) // conversion from json to typed class 
.subscribe(i => {this.ng2TableData.push(i);}) //subscribe 

在最后一行,我希望订阅方法立刻提供给我的整个列表,而不是它似乎obsevable被返回的时候一个Incident和订阅功能称为N次,因此迫使我采用push方法,而不是一次构建ng2TableData

我该如何订阅整个列表,而不是当时的一个项目?

+3

那么不要使用'flatMap',因为'flatMap'会将你的数组值平化为一个可观察的值流。 – Alex

+1

为什么你甚至首先使用flatMap? –

+0

但是,如果我使用map而不是flatmap,那么在第二张地图中,我将输入的是整个数组而不是单个事件。用map而不是flatmap来做这件事的正确方法是什么? – LucaV

回答

1

flatMap将使您的数组变为可观察的值流。你只想使用map。您可以再次使用map,使每个对象数组中为你的类的实例,像这样:

this.server.get("incidents") 
    .map(res => res.value.map(incident => new Incident(incident))) 
    .subscribe(data => console.log(data)) // data is an array! 

现在你得到你的阵列里,而不是订阅。

+0

谢谢你的帮助,就是这样!很明显,一旦你写了它,但在我的脑海中,解决方案是rxjs方法的连接,而不是嵌套的映射方法 – LucaV

相关问题