Tips for asynchronously adding data (requires two iterations) to an API service in Angular

I have a json file structured as follows:

{
  "users": [
    {
      "id": "person1",
      "information": [
        {
        "first_name": "Mike",
        "last_name": "Patty",
        "address": ["address1","address2"]
        },
        {
          "first_name": "Mike2",
          "last_name": "Patty2",
          "address": ["address1","address2"]
        }
      ]
    },
    {
      "id": "person2",
      "information": [
        {
        "first_name": "Tom",
        "last_name": "Jerry",
        "address": ["address1","address2"]
        },
        {
          "first_name": "Tom2",
          "last_name": "Jerry2",
          "address": ["address1","address2"]
        }
      ]
    }
  ]
}

My goal is to loop through each user's data and input it into the API database using the addInfo request. This request needs the fields: first_name, last_name, and address (an array). This is necessary in order to store the response from the information request for future reference.. I am relatively new to working with angular/typescript, so here is my attempt at coding this so far:

Thank you very much!

Answer №1

When using forkJoin, you need to provide an array of observables, execute them, and return the response of each observable once all are completed. To achieve this, you must create an array of observables by converting your existing "users" array into an array of API calls using the "map" function.

const addUsers$ = forkJoin(
User.map(x=>
  //each "x" contains {id:..,information:{first_name:..,last_name:..,address:..}
  this.APIservice.addInformation(
           {
              firstName: x.information.first_name,
              lastName: x.information.last_name,
              organizations: x.information.address
           }
      )).subscribe((res:any[])=>{
            //res[0] will hold the response from the first API call, 
            //res[1] will hold the response from the second API call
            //...

      })

Answer №2

Give flatMap a shot

const mergeUsers$ = forkJoin(
     Users.flatMap(user => user.information).map(info => 
       this.APIservice.addInformation(
           {
              firstName: info.first_name,
              lastName: info.last_name,
              organizations: info.address
           }
      )))
   );

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

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Conceal a table if it has no content

I am dealing with 2 tables that contain various data sets. img01 If both of my tables happen to be empty, I would prefer them to be hidden. img02 Is it feasible to implement this in Angular? If you have a solution for me, I would be eager to give it a ...

The "number" input type is functioning correctly on Chrome, but on Firefox, it is accepting characters other than numbers

While developing in Angular, I encountered a challenge where I needed to create an input that only accepts numeric characters. Initially, I tried using type="number" which worked perfectly in Google Chrome but surprisingly allowed non-numeric characters ...

What is the method for identifying the points where two faces of two bufferGeometryBox objects intersect?

I am currently working on a 3D configurator project. In this project, a cube is initially displayed on the scene. When a side of the cube is clicked, a rectangle is supposed to appear. However, the issue I am facing is that upon clicking the same side of t ...

Utilizing NgStyle and Property Binding in Angular to Manipulate Data (or a Different Approach)

Currently, I am diving into Angular programming and encountering an issue with property bindings. Let me share a snippet of my code: // TS FILE data[ {"id": "1", "name": "tester", "rev": "1"}, {"id": "2", "name": "tester", "rev": "1"}, {"id": "3", "name" ...

Color scheme for navigation bar carousel item background color

I have a navigation bar and carousel within the same section. I want to change the background color of both the navigation bar and carousel item when the carousel indicator becomes active. Any suggestions on how to achieve this using a jQuery function? H ...

Angular version 4 is used to retrieve deeply nested JSON data

How do I extract data from a nested JSON file? Here is an example of the JSON structure: { "user1": { "name": "john", "surname": "johnsson" }, "user2": { "name": "Jacob", "surname": "Jacobsson" } } I want t ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

Merge Razor with Ajax and JSON

I have been struggling to get the following components to work together without success. The goal is to populate the mediaId's combobox with respective values based on the selection in the target combobox. Currently, I am only simulating the values fo ...

Ways to activate a function upon validation of an email input type

Within my HTML form, there is an input type="email" field that requires a valid email pattern for acceptance. I am attempting to send an AJAX request to the server to confirm whether the entered email already exists in the database after it has been verif ...

What is the best way to split an AJAX response into different variables and effectively retrieve each one of them?

When using AJAX to fetch data from a database and display it in a text box, most examples found online only show how to display the AJAX response in one text box. But what if we need to separate multiple PHP variables retrieved from the AJAX response and d ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

What is the best way for a server to set up middleware chaining?

Currently, I am facing challenges in grasping the concept behind the ExpressJS module, particularly focusing on the execution of middleware chains. My main goal is to comprehend how a server can listen for incoming requests, and once received, pass the re ...

Encountering an error when utilizing Angular Animation with Bootstrap -> Issue arises from attempting to read properties of undefined (specifically 'box-sizing')

To access the source code of Git, visit https://github.com/codezj/exampleAppAnimation. I recently developed a method to extract Bootstrap CSS and utilize it as CSS in Angular. However, I encountered an error while running the Angular project: Uncaught Typ ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

Validation of md-datepicker and md-select in Angular MaterialAnguar Material validation

I am working on a form that includes input fields, datepickers, and dropdowns. Currently, if the required input fields are left blank upon submission, they are highlighted with a red line. However, I want the datepickers and dropdowns to also be highlighte ...

What is the best way to display multiple sets of table data on a single page without any connections between them?

Is there a way to combine data from two tables (dept_db, role_db) and display it on my createUsers page? I am looking for a solution where the page only needs to be rendered once to retain the previous query results. Thank you. exports.createUsers = func ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

NodeJS error message: "The callback provided is not a function

As someone new to the world of NodeJS, I'm facing challenges in understanding how to pass variables and objects between functions. Any help on what I might be doing wrong would be greatly appreciated. Let's take a look at this code snippet: Inc ...