【问题标题】:How to loop through an observable in Angular 4如何遍历Angular 4中的可观察对象
【发布时间】:2017-10-08 12:04:03
【问题描述】:

我有一组部分,我正在尝试获取并显示每个部分下的所有项目。这似乎是一个非常简单的方法。这是我的代码:

//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; 

}

也许我上面的解释不太清楚 所以我想做的是在一个循环中多次调用我的网络服务并将结果连接到一个列表中。也许这会有所帮助。

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.

希望对你有所帮助。

【问题讨论】:

    标签: angular loops rxjs observable


    【解决方案1】:

    问题可能出在您的 http 流上:res.json() 返回解析为 json 的响应正文。 所以你应该使用 .map() 运算符,而不是 .mergeMap() 运算符。

    前者只是将转换函数应用于每个流数据并将结果通过管道传输(这就是您所需要的),后者将一个 observable 的所有值投影到您的流中(这不是您所需要的)。

    一些参考资料:

    希望对你有帮助:)

    ** 更新 **

    好的,我误解了您的需求:您需要将所有 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); 
    }
    

    这段代码我是直接写在这里的,所以可能行不通,但是背后的思路应该是你需要的:)

    【讨论】:

    • 如果我使用地图,系统只会从第一部分提取项目,但如果我使用 mergeMap,我会收到此错误“找不到类型为 'object' 的不同支持对象 '[object Object]' . NgFor 仅支持绑定到 Iterables,例如 Arrays。”我只想显示所有选定部分的所有项目。那有意义吗?如何将我从 Web 服务收到的所有记录合并或连接到 1 个 observable 中?
    • 好的,现在我理解了您的需求,但是您的代码做了一些不同的事情:您正在覆盖 resultObservable 变量的 SectionItems 的每个循环。我尝试相应地更新我的答案:)
    • 非常感谢洛伦佐。您的回答将每个调用分成数组。我只需要弄清楚如何连接这些数组。我想我应该能够弄清楚这一点。再次感谢。
    猜你喜欢
    • 2018-03-01
    • 2019-06-02
    • 1970-01-01
    • 2018-04-11
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多