What is the process for list.map to handle waiting for a request response?

I'm facing an issue with my map function where it is not waiting for the request response before moving on to the next index.

this.products = [];
productList.map((product) => {
this.productService.getProductInfo(product).subscribe(productData => {
   productData.selected = true;
   this.products.push(productData);
  });
});

Is there a way to make the map function wait for the request response?

Answer №1

To start, create an array of requests:

const productRequests: Observable<Product>[] = productList.map(productId => this.productService.getProductInfo(productId));

Next, to combine the observables, there are a few ways to do it while preserving the order:

// Loads all at once, preserves order
forkJoin(...productRequests).subscribe(productData => {
  this.products = productData;
});

or

// Loads one by one, sorts post result to preserve order
this.products = [];
merge(...productRequests).subscribe(productData => {
  this.products.push(productData);
  this.products.sort((a, b) => {
    if (a.id < b.id) {
      return -1
    }
    if (a.id > b.id) {
      return 1
    }
    return 0;
  });
});

Link to Code Example

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 methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...

Revise the classification of an instance variable within a subclass

I am pondering about the topic of inheritance and types for instance variables in typescript. Consider a basic class as shown below: class Person { instanceVariable: Object; age: Number; constructor(instanceVariable: Object, age: Number) { this ...

How to import a node module into an Angular app through Angular CLI and load children in

My goal is to import a module from the node modules. This particular node module contains routes that I need to access. Here's what I want to achieve: I aim to configure my app.module to incorporate loadChildren from the module within my node module ...

Ensuring Type Compatibility Between Classes and Object Literals in TypeScript

When working with TypeScript, it is important to note that an object literal can be assigned to a class typed variable as long as the object provides all properties and methods required by the class. class MyClass { a: number; b: string; } // The co ...

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

Sending print jobs to an HTTP printer from an HTTPS connection using Angular 6

Currently, I have an Angular 6 application set up with Nginx and HTTPS. However, I am facing an issue when trying to send commands to my ZPL printer for label printing. The problem lies in the fact that the printer only accepts HTTP protocol, but the brows ...

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Error encountered in Typescript when handling fetch options as a variable

Why does this code compile perfectly? fetch('someurl', { method: 'GET', credentials:"same-origin" }) However, the following code throws a compilation error for fetch('someurl', init); const init = { method: &apo ...

Customize the color when clicking on a mat-slide-toggle

Whenever I click on the element, a shadow appears in the color that corresponds to the element, which is currently yellow https://i.sstatic.net/21BR4.png I would like to change that shadow to be green instead, but I am unsure of how to do so. Here is my ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

The absence of @angular/forms/FormsModule is causing issues

I am facing an issue with importing the FormsModule from @angular/[email protected] while working with Angular 2 RC5. It seems like a simple task, but I am encountering difficulties. import { FormsModule } from '@angular/forms'; Surprising ...

Tips for positioning a div alongside its parent div

I have a unique setup with two nested divs that are both draggable. When I move the parent div (moveablecontainer), the child div (box.opened) follows smoothly as programmed. Everything works well in this scenario. However, when I resize the browser windo ...

ESLint is indicating an error when attempting to import the screen from @testing-library/react

After importing the screen function from @testing-library/react, I encountered an ESLint error: ESLint: screen not found in '@testing-library/react'(import/named) // render is imported properly import { render, screen } from '@testing-lib ...

A step-by-step guide on creating a user-specific signature in Node.js

Is there a way to incorporate user-generated signatures similar to how Amazon delivery personnel have recipients sign on their mobile devices using NodeJS? Any helpful resources would be greatly appreciated. I am working with Angular for the frontend and ...

Vue.js 3 with TypeScript is throwing an error: "Module 'xxxxxx' cannot be located, or its corresponding type declarations are missing."

I developed a pagination plugin using Vue JS 2, but encountered an error when trying to integrate it into a project that uses Vue 3 with TypeScript. The error message displayed is 'Cannot find module 'l-pagination' or its corresponding type ...

Error loading ngsw-worker.js in Angular 7

Issue An app that utilizes a Service Worker is experiencing problems. The app was recently upgraded from Angular 6.1 to version 7. Upon uploading the updated files to the server, an error message is displayed: https://i.sstatic.net/B7uPf.png Error Det ...

Implementing form validation in Angular2 without using the <form> tag

Is there a way to perform form validation in Angular 2 without using the typical form tag setup? For instance, I would like to set a required field below: <div class="form-group"> <label for="name">Name</label> <input type=" ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...