2017-10-08 105 views
-2

我有一個部分數組,我試圖獲取並顯示每個部分下的所有項目。這似乎是一個非常簡單的要求。這裏是我的代碼:如何在Angular中循環觀察值4

//my ngOnInit call this function 
this.sectionService.GetItemList(this.selectedSectionList, this.culture)  
     .subscribe(
      (itemList: ItemBySection[]) => { 
       this.itemBySection = itemList; 

       this.loaded = true; 
      }, 
      (error: any) => this.errorMessage = error,() => 
console.log("loaded") 
     ); 

//this is my function in my service 
public GetItemList(SectionItems: Sections[], strCulture): Observable<ItemBySection[]> { 

    let resultObservable 
    for (var SectionItem in SectionItems) { 
     let url = environment.portalWebServiceURL + "api/section/" + SectionItems[SectionItem].sectionItemID.toString() + "/" + strCulture; 
     resultObservable = this.http.get(url) 
      .catch(this.handleError) 
      .mergeMap(res => <ItemBySection[]>res.json()); 
    } 

    return resultObservable; 

} 

也許我上面的解釋是不是太清楚 那麼我現在要做的是調用一個循環中我的web服務的多個時間和結果連接成一個列表。也許這會有所幫助。

for all my sectionIDs { 
    call url web service with sectionID 
    receive results from server 
    add the results in my item array 
} 
finally display all items. 

我希望這可以幫到你。

回答

1

可能問題在於你的http流:res.json()返回解析爲json的響應正文。 所以你應該使用.map()運算符,而不是.mergeMap()運算符。

前者只是將轉換函數應用於每個流數據並對結果進行流水處理(這就是您需要的),後者將一個observable的所有值投影到流中(而這不是您需要的)。

一些參考:

希望它能幫助:)

**更新* *

好的,我誤解了你的需求:你需要d在一系列響應中加入所有http響應。 你可以做這樣的事情:

public GetItemList(SectionItems: Sections[], strCulture): Observable<ItemBySection[]> { 
    const resultObservables = [] 
    for (var SectionItem in SectionItems) { 
     let url = environment.portalWebServiceURL + "api/section/" + SectionItems[SectionItem].sectionItemID.toString() + "/" + strCulture; 
     const response = this.http.get(url) 
      .catch(this.handleError) 
      .map(res => <ItemBySection>res.json()); 
     resultObservables.push(response) 
    } 
    return Observable.forkJoin(resultObservables); 
} 

我寫了這個代碼直接在這裏,所以它可能不會工作,但它背後的想法應該是你所需要的:)

+0

如果我使用映射系統只從第一部分拿起項目,但是如果我使用mergeMap,我得到這個錯誤「無法找到'object'類型的不同支持對象'[object Object]',NgFor只支持綁定到Iterables,比如數組。我只想顯示所有選定部分的所有項目。那有意義嗎?我如何將從Web服務接收到的所有記錄合併或連接成1個可觀察對象? –

+0

好吧,現在我不明白你的需求,但你的代碼做了一些dirrefent:你正在覆蓋resultObservable變量的SectionItems的每個循環。 我嘗試相應地更新我的答案:) –

+0

非常感謝洛倫佐。你的回答將每次調用分隔成數組。我只需要弄清楚如何連接這些數組。我想我應該能夠弄清楚。再次感謝。 –