Recently, I encountered an issue while working on a service call to retrieve data from a JSON file containing multiple items. After fetching all the items, I needed to make another service call to retrieve the contents of each item. I tried using flatMap for this purpose but faced difficulty in passing parameters - whenever I attempted to do so, it would get underlined as an error in the code.
Here is the snippet of my data call:
getItems(){
this.itemService.getItemsData().flatMap(
data => {this.items = data;
error => this.errorMessage = <any>error;
return this.itemService.getItemContent();
}).subscribe(data => {
this.itemContent = data;
});
}
Whenever I tried passing parameters into
...getItemContent(this.items.contentUri)
, it resulted in an error.
getItemsData(){
return this._http.get(url)
.map((res:Response) => res.json())
.map((obj) => Object.keys(obj).map((key)=>{return obj[key]}))
.catch(this.handleError);
}
getItemContent(uri){
return this._http.get(uri)
.map((res:Response) => res.json())
.catch(this.handleError);
}
I am seeking guidance on how to effectively handle this scenario so that when retrieving items, I can also fetch the corresponding item contents based on a parameter.
Below is an insight into the JSON structure:
{
Item 1: {
title:....
id:....
content:{
uri:"link"
}
}
}
UPDATE:
getItems(){
this.itemService.getItemsData().flatMap(
data => {this.items = data;
for(let x of data){
var url = x.content.uri;
this.observables.push(this.itemService.getInnerItemData(url));
}
return Observable.forkJoin(this.observables);
}).subscribe(data => {
this.itemsContent = data;
});
}
HTML:
<div *ngFor="let item of items">
{{item.title}}
<div *ngFor="let content of itemsContent">
{{content.infoText}}
</div>
</div>
In my display, the item.title
is being rendered correctly as expected. However, the content within each item appears as an array of [object][object]
. It seems like all the itemsContent
are displayed for every item without any specific association with the respective item.