Subscribing to a nested Observable

前端 未结 3 795
遇见更好的自我
遇见更好的自我 2020-12-02 02:13

I have an app that makes one http request to get a list of items and then makes an http request for each item in the list to get more detailed information about each item.

3条回答
  •  天命终不由人
    2020-12-02 02:47

    You can break up the items array before the line that calls this.fetchItem. You can use mergeMap on an Observable whose value is an array and each item will be emitted individually.

    fetchItems() {
        return this.http.get(url)
           .map(res => res.json())
           .mergeMap(arrItem => this.fetchItem(arrItem));
    }
    

    Edit: I guess I should have provided more explanation. mergeMap is synonymous with flatMap in rxjs. Typically, you use flatMap when your projection function returns an Observable, but it will also flatten arrays as well, so, calling mergeMap will then emit each item individually, I thought that was what OP wanted to achieve. I also realized, you can combine the mergeMap call and last map call, because the projection for mergeMap will be called for each item in the array, I made the changes in the code above.

提交回复
热议问题