Using Angular's mergeMap feature to concatenate multiple HTTP calls sequentially

The method called getDetails() retrieves an array of Details[]. Within this array, there is a property named name which I need to pass to another HTTP request.

Details {
    name: String;

Details

 getDetails()
     return this.https.get("/someValue")

return

{name : hello}

Information

 getInformations(name:string) {
    return this.https.get("/anotherValue"+"?"+ name)
 }

I am attempting to first call the getDetails() method and then pass the extracted name property to

Information{
  Hieght:string
  age:string
}

getInformations()
this.getDetails().pipe(mergeMap(x => 
 this.getInformations(x.name)).subscribe((inforamtionResults:Information[])=>{
  console.log("Checking Informations"+inforamtionResults.length) 

return

 {height:160,
   age: 23
   }

This approach is not functioning properly as the value of x is an array. How can I iterate over the array and pass each item's property as a parameter?

Answer №1

To achieve the desired outcome, it is necessary to iterate through each this.getInformations(x.id) Details. This can be accomplished by utilizing the Array.map() method. However, since mergeMap expects a single observable while we have an array of observables, we can consolidate these observables into one using rxjs' forkJoin.

this.getDetails()
  .pipe(
    mergeMap((details) =>
      forkJoin(details.map((x) => this.getInformations(x.id)))
    )
  )
  .subscribe((x) => console.log(x));

For further clarification and demonstration, refer to this sample demo. Although a different API is used, the implementation remains consistent.

Answer №2

It is essential to attempt it in this manner.

 fetchInformation() {
    return this.http.get("/someValue")
      .pipe(
        mergeMap((x) => {
          return this.retrieveDetails(x.id)
        })
      );
  }

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

Developing a bespoke React Typescript button with a custom design and implementing an onClick event function

Currently, I am in the process of developing a custom button component for a React Typescript project utilizing React Hooks and Styled components. // Button.tsx import React, { MouseEvent } from "react"; import styled from "styled-components"; export int ...

Is it Mission Impossible to Combine NodeJs, Restify, SQL Server, TypeScript, and IIS?

Starting a Rest API project using NodeJS with Restify on a Windows environment (local server with IIS and SQLServer) while also using Typescript may seem like a difficult task. Is it an impossible mission? Does anyone have any helpful guides, documentatio ...

Using Angular's ngFor directive to iterate over a collection based on a true

I am currently attempting to resolve the following condition: if the condition is true, display a button, otherwise hide the button. OfferMatching() { this.getmatchoffer.filter(obj => { debugger for (let i = 0; i < this.applicationJobList.length; i+ ...

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

The label overlay for MatInput remains fixed within the input box in an Angular form

I've encountered an issue with some of my form fields where the field label doesn't move up to the top border of the field when you start typing in the input box. Instead, it remains in the middle of the box, causing the characters you type to ov ...

Top tips for accessing and modifying an immutable object within a component retrieved from an RXJS/NGRX store in Angular

This week we successfully updated our Angular v9 app to v11 and RXJS v6.6 with minimal issues. However, due to the store being in freeze mode, we are encountering errors when trying to update the store in certain areas of our code. While most of the issue ...

Is it possible for me to download npm locally using the command line? I am looking to install an older version of npm for a project that requires it

I currently have two Angular projects on my computer: The first project is built in Angular 14 and connected to Java. The installations of npm and ng are carried out using Maven plugins. Here is an example of the Maven plugins being called with configurat ...

Angular 4 CanActivateChild fails to function

I'm attempting to limit access to my route system by using the CanActivateChild feature. However, I've encountered an issue where the RouteGuard only works with the CanActivate function and not CanActivateChild. Here's a snippet of my routin ...

Creating an abstract static factory with a protected constructor in Typescript

I've been working on this code snippet: import { IValueObject } from "../../shared/domain/IValueObject"; import { AbstractNanoidGenerator } from "../../shared/infrastructure/AbstractNanoidGenerator"; export class CompanyID extends ...

Error in parsing: Unexpected token encountered. Expected a comma instead. Issue found in React with Typescript

I'm encountering a new error message that I haven't seen before... I've checked my code thoroughly and it seems to be correct, yet the error persists. Here is my code snippet: interface AuthState { token: string; user: User; } interfac ...

An array becomes undefined once the previous array is removed

Consider the following code snippet: using the splice method, a specific item from Array1 is retrieved and stored in a variable called Popped. Next, Popped is added to array2. However, if we then delete the value from Popped, why does array2 become undef ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Utilizing logical operators to assign values to variables in Typescript

export class SearchResult { id: string; constructor(obj?: any) { this.id = obj && obj.id || null; } } Can someone explain to me the meaning of obj && obj.id || null? I'm confused by this syntax. ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

Utilizing the moment function within an Angular application

I've successfully added the library moment.js by running: npm i moment I've included it in scripts and attempted to import it in module.ts. However, when I try to use moment in component.ts, I'm getting an error that says: 'canno ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

To activate the ion-toggle, simply click on the ion-label

Currently, I am in the process of developing a page using Ionic 5. One of the features I am including is a 'remember me' button which utilizes <ion-toggle>. <ion-item> <ion-label>remember me</ion-label> <ion-to ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...