Performing several HTTP requests in a for loop in Angular 8

Within the backend, there exists an endless list of cars. Each car is designated by a unique id and has a corresponding model name.

I possess a compilation of car IDs, as illustrated below:

const carIds = ['abc','xyz'];

My objective is to retrieve the names that correspond to the aforementioned car IDs. Although I initially attempted the following code, it unfortunately failed to produce the desired results. Could you please identify what might be missing?

const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // Despite executing this code snippet, no output is generated.

The anticipated output should resemble the following structure:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]

Your assistance is greatly appreciated.

Answer №1

Utilizing the forkJoin method allows you to simultaneously subscribe to multiple streams and receive the combined result when all streams have completed, analogous to a promise.all for rxjs.

const uniqueCarIds = ['abc', 'xyz']; // unique ids
const httpRequests = uniqueCarIds.map(id => this.api.getCar(id)); // array of streams
const cars$ = forkJoin(httpRequests).pipe(
   map(results => results.map((result, index) => ({ id: uniqueCarIds[index], name: result.name }))
);

cars$.subscribe(console.log);

Answer №2

let vehicles = [];

for await (const vehicleId of vehicleIds) {
  const carData = await this.api.getCar(vehicleId);
  carData && vehicles.push({
        modelName: carData.modelName,
        vehicleId: vehicleId
      });
}

Feel free to test out this snippet. Let me know if you have any questions!

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

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Is it possible to implement cross-field validation with Angular 2 using model-based addErrors?

Currently, I am working on implementing cross-field validation for two fields within a form using a reactive/model based approach. However, I am facing an issue regarding how to correctly add an error to the existing Error List of a form control. Form: ...

ways to display selected custom information with a choiceLabel in a dropdown using primeng

Is there a way to display custom data on a dropdown in Primeng while also showing the selected data as shown in the dropdown list? Please refer to both images below for clarification. <div class="p-grid" *ngIf="deleteUser" style=&quo ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to lear ...

Navigating away from an Ionic 2 app running in the browser and then returning: tips and tricks

Currently, I am setting up my oauth2 authentication in Ionic2. Through my research, I have discovered that the Cordova InAppBrowser plugin can be utilized to handle the process of navigating to the website and granting access to the App. However, I am st ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

React Typescript: Turn off spellchecking

Struggling to turn off spell check for typescript <form> <input type='text' name='accountName' ref={accountName} onChange={checkName} spellCheck='false' // <====== Disable spellche ...

What is the best approach to incorporate a refresh feature for a data stream?

I need to implement a function that updates the current list of items$ and allows for awaiting refreshItems(). This is my working implementation: private readStream = new Subject<T[]>(); readStream$ = this.readStream.asObservable(); getItems = (): ...

The ngx-translate/core is throwing an error message that says: "HttpClient provider not found!"

I recently downloaded the ngx-translate/core package and have been diligently following the provided documentation. However, I'm facing an issue with getting the translations to work. Here are the steps I've taken: 1] Definition in the AppModul ...

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

TypeScript Redux Thunk: Simplifying State Management

Seeking a deeper understanding of the ThunkDispatch function in TypeScript while working with Redux and thunk. Here is some code I found: // Example of using redux-thunk import { Middleware, Action, AnyAction } from "redux"; export interface ThunkDispatc ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

Leveraging default values in generic implementations

Imagine a scenario where the following code is present: type QueryResult<ResultType = string, ErrorType = string> = { result: ResultType, } | { errors: ErrorType, } So, if I want to initialize my result, I can proceed like this: const myResult: ...