Utilizing flatMap to implement nested service calls with parameters

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.

Answer №1

To execute multiple requests in parallel, utilize the forkJoin method.

getItems(){
    this.itemService.getItemsData().flatMap(
      data => {
      this.items = data;
      var observables = [];
      for(let x of data){
          var url = x.content.uri;
          observables.push(this.itemService.getItemContent(url));
      }
      return Observable.forkJoin(observables);
    }).subscribe(data => {
        console.log(data);
    });
}

Upon subscribing, you will receive an array containing responses for each item's content.

Update

If you want to display each item's content based on their index in the view, consider implementing the following:

<div *ngFor="let item of items; let i = index;">
    {{item.title}}
    <dic>
        {{itemsContent[i]?.infoText}}
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best Java framework to use for developing an AJAX application?

After combing through various discussions on forums about basic Java web frameworks and Java web development, I realized that most do not touch upon the AJAX aspect. For the project I am currently working on, a significant portion of the client-side work w ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...

What sets the do/tap operator apart from other observable operators?

Can anyone clarify the distinction in simple terms between the typical observable operators used for observing output and why do/tap appear to serve the same purpose? What is the reason for utilizing do/tap? ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

Flutter: a feature that checks all checkboxes

(Resolved) Previously encountered an issue (now resolved) where selecting one checkbox resulted in all checkboxes being selected. View the image below for reference: (Unresolved) Seeking assistance from someone experienced with using checkboxes in Flutt ...

JSON data is being displayed in the spinner for just a single item

My spinner is supposed to display all of the supplier's names from a JSON file. I managed to retrieve the JSON data, store it in an ArrayList, and display it. However, I encountered an issue where only one item is displayed - usually the most recently ...

Exploring JSON encoding specifics

While exploring the concise language specification of JSON, I came across a surprising sentence: Aside from a few encoding nuances, that statement fully encapsulates the language. What specific details have the potential to challenge those straightforwar ...

Leveraging TypeScript to share information between directives in AngularJS through asynchronous calls

Although I've found some scattered information on how to tackle this issue, I haven't been able to find a solid solution. In my AngularJS application, I have an asynchronous call that fetches data from a server and I need to store it in a variab ...

Can a star rating be generated from a JSON value?

I'm curious if it's possible to display a glyphicon-star based on the value in a JSON file using AJAX. Here is an example of my JSON file: [ { "star": 4 },{ "star": 3 },{ "star": 5 } ] Here is my AJAX code: $(function($){ ...

Determine the number of distinct property values within a JSON API response

Running on a Ruby on Rails backend, I have a JSON API that serves an array of objects with the following structure: { "title_slug": "16-gaijin-games-bittrip-beat-linux-tar-gz", "platform": "Linux", "format": ".tar.gz", "title": "BIT.TRIP BEAT", ...

Update the database with the information provided by this model using Ajax technology

There is an Ajax function in my View that I am having trouble with. function Save() { var Url = '@Url.Action("UpdateCaseDetails", "CaseDetailView")'; var frm = $("form"); var data = JSON.stringify(frm.serializeArray()); $.ajax({ ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...

Transforming the contents of a folder into a json document

I have a collection of files in directory A with the .txt extension, and I'm looking to create a JSON file for this specific directory (A) from another directory (B) that includes the names and locations of all the files. Can anyone guide me on how I ...

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

Conceal the legend in Highcharts using Python script with Django

Need some assistance with a Django and Highcharts.js project I'm working on. Objective: hide the legend in a Highcharts chart from my views.py script. In my views.py file, I've successfully plotted various charts but struggling to hide the lege ...

Accessing variables outside of an exception block in Python

When making an API call using the Python urllib library, the API may throw an error when something unexpected occurs (e.g. HTTP Error 415: Unsupported Media Type). However, alongside this error message, the API also returns a JSON object with more detailed ...

Dealing with various node types in a parse tree using TypeScript: Tips and Tricks

I am in the process of converting my lexer and parser to TypeScript. You can find the current JavaScript-only code here. To simplify, I have created an example pseudocode: type X = { type: string } type A = X & { list: Array<A | B | C> } ty ...

RecyclerView not showing JSONArray items

I encountered an issue with the following error message: org.json.JSONException: End of input at character 0 of... I have verified the correctness of my JSON data using Postman, and it appears to be valid. To further investigate, I added static values ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...