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

Is angular.io an enhanced iteration of angularjs?

Is learning angular.io significantly different in terms of coding compared to AngularJS? Which one would be the better choice for me to learn and why? ...

An entire line of boxes has been checked off

Currently, I am working on adding an additional column with checkboxes to the Mat table example. However, I noticed that when I click on one checkbox in a column, the checkboxes in other columns also get selected. How can I implement this so that only th ...

Updating content in Angular 2 using PUT method with the "uri/list" content type for multiple elements

What is the process for sending multiple elements in a PUT request using Angular 2 and Typescript? In order to send multiple URIs, they must be separated by a line break: curl -i -X PUT -H "Content-Type:text/uri-list" --data-binary @uris.txt http://loc ...

Angular is generating local caches of NPM packages within the designated .angular folder

Is there a way to turn off the caching in the main Angular project directory? I noticed this issue after setting up NVM last week. https://i.sstatic.net/zFnGy.png ...

Tips for monitoring/faking method invocations within an Angular 5 service's constructor

My service involves making 2 method calls in the constructor: constructor(private http: HttpClient) { this.apiURL = environment.apiURL; this.method(); this.method2().subscribe(); } I am facing difficulties testing this service in the Test ...

Struggling to transfer information between different components?

I recently implemented a delete button functionality in my project to remove elements when clicked, but I'm facing an issue where the input decorator is not properly receiving data for deletion. When I console log, it shows that the array is empty whi ...

The issue with ngModel in Angular is that it fails to update the value within the component

My ngModel doesn't seem to be functioning properly when I use it with a textbox in my application. This is the code snippet from app.component.html: <input type="text" [value]="name" [ngModel]="name"> Name is: {{na ...

Exploring Query String Retrieval and Data Fetching in Ionic 2 using Angular 4's $

I am struggling to find the information I need, so I'm reaching out for help on how to send a request to a JSON api with parameters encoded in JavaScript. It is crucial that the parameters are properly encoded because the query could contain special ...

Can you showcase two distinct perspectives on a single page?

One of my components has nested ngFor directives looping through an array of users and their posts. I have a view link within this element, and when clicked, it should show detailed information about both the user and the post. However, the current setup i ...

The datepicker in Angular 2 is not displayed properly in Firefox when using the input with the type=date attribute

Everything is functioning properly in the Chrome browser. <div class="form-group"> <label for="date">Date:</label> <input class="form-control " [(ngModel)]="journal.record.date" type="date" required/> </div> <br/& ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

Encountered an error while trying to install a package using NPM due to the requirement of 'require-from-string@

Every time I try to install a package (even nodejs), I encounter this issue. Here is what I have tried so far: Uninstalled all dependencies Cleared cache Reinstalled NPM / AngularCli Unfortunately, running any NPM command still results in the same error ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Guide on how to duplicate a form upon clicking an "add" link in Angular 2

Is it possible to dynamically repeat a form in Angular2 when clicking on a link? I am looking for a way to add the same form below the previous one when a specific link is clicked. Any suggestions or immediate replies would be greatly appreciated. For ins ...

Sharing information from Directive to Component in Angular

Here is a special directive that detects key strokes on any component: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[keyCatcher]' }) export class keyCatcher { @HostListener('document:keydo ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

Using Angular to assign a CSS variable to the before/after pseudo-classes

Having trouble passing a variable with [ngStyle] and reading it on the ::before class, any guidance in the right direction would be much appreciated! CSS: .handle-slider__control { height: 7px; z-index:1; background: $colour-alto; positi ...

There are no versions available for Angular NPM that match [email protected]

Here is the contents of my .npmrc file: registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true After deleting node_modules and attempting to install the packages, I encountered the follo ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Angular Universal does not handle serving static files

I have a straightforward Angular Universal SSR (server-side rendering) application that is functioning well. The server successfully renders the HTML, but I am encountering an issue with static assets such as fonts, images, and icons not loading via the se ...