2017-12-03 155 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

相關問題