2017-06-06 28 views
1

不幸的是,這樣的網站是設置,我需要檢索的數據,是該數據在多個站點傳播(類型完全相同的數據和JSON返回格式),但它們位於不同的URL。他們被URL分類,所以我確實需要保留這些URL,以便在整個應用程序中對其進行進一步分類。我有以下服務功能,我正在嘗試傳遞一組主題(然後傳遞給URL),檢索數據並返回單個可觀察項。然而,這回什麼:角服務功能不返回任何東西,嘗試做多個HTTP請求,並返回單一可觀察

getDataTopicItems(topicArray) { 
    return this.items = topicArray.forEach((topic, i, topicArray) => { 
     return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options) 
      .map(res => res.json()) 
      .map(items => items.d.results) 
      .do(data => console.log(data)) 
      .concatMap(data => data) 
     } 
    ) 
} 

我訂閱了它在我通過* ngFor加上一個異步管道調用這個函數組件的模板。我究竟做錯了什麼?

更新:我也試過如下:

return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options) 
      .map(res => res.json()) 
      .map(items => this.policies = items.d.results) 
      .do(data => console.log(data)) 
      .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => { 
       if (i < 0) { 
        this.http.get(this.baseUrl + topic + this.policyOptions) 
         .map(res => res.json()) 
         .map(items => this.policies = items.d.results) 
         .do(data => console.log(data)) 
       } 
      })) 

回答

1

Array.prototype.forEach回報undefinedSee MDN for documentation。使用Array.prototype.map,而是和this.items將觀測,你可以再要與什麼做的數組。

+0

更改的forEach映射也不起作用。在這兩種情況下,它都沒有console.log數據。 – kittycatbytes

4

Array.forEach方法的回調函數並不期望收到任何東西,所以也許你想用Array.map來代替。

如果你正在尋找「更RxJS」接近你可以使用mergeMap做這樣的事情:

return Observable.from(topicArray) 
    .mergeMap(topic => this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options) 
     .map(res => res.json()) 
     .map(items => items.d.results) 
     .do(data => console.log(data)) 
     .concatMap(data => data); 

最終,你可以使用concatMap,而不是mergeMap運行爲了所有請求,並使用concatAll代替.concatMap(data => data);這使得它更明顯,你正在嘗試做什麼。

順便說一句,請注意,通過使用this.items = ...您只需將一個Observable分配給this.items而不是結果。

另外請注意,您需要訂閱返回可觀察到,如果你想獲得任何結果。例如:

getDataTopicItems([...]).subscribe(result => this.items = result); 

見現場演示:https://jsbin.com/nuzifo/9/edit?html,js,console

+0

感謝你爲這個 - 我怎麼會訂閱結果,而不是項目?現在我正在修改我的代碼以獲得this.http的返回值,並刪除上面的所有內容,如下所示: '' return this.http.get(this.baseUrl + topicArray [0] +「/ _api/Web /列表/ GetByTitle( '什麼' 的新')/項目」,this.options) .MAP(RES => res.json()) .MAP(項目=> items.d.results) 。做( data => console.log(data)) .flatMap(data => topicArray.forEach((topic,i,topicArray)=> {在此處繪製更多代碼} – kittycatbytes

+0

@kittycatbytes我不確定你的意思。說起'您分配可觀察到的,但是從它的名字,它看起來像你期望的可觀測鏈的結果分配給它this.items'財產。 – martin

+0

如果你使用'topicArray.map(.... )'用你現在的代碼編寫一個Observabl這可能不是你想要的。 – martin

相關問題