Populating fields in one observable with data from a different observable in Typescript

Can someone help me with two requests?

/users and /user/<id>/milpac

/users returns a list of User[], while /user/<id>/milpac returns a milpac object.

export class User {
  join_date: string;
  promotion_date: string;
  user_id: number;
  username: string;
  milpac: Milpac;
}

export class Milpac {

  user_id: number;
  milpac_id: number;
  real_name: string;
  username: string;
  rank: string;
  rank_shorthand: string;
  status: string;
  primary_position: string;
  bio: string;
  join_date: string;
  promotion_date: string;
}

First, I fetched all users using:

getAll(): Observable<User[]> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.API_AUTH_HEADER
    });
    const options = { headers: headers };
    return this.http.get<UserResult>(this.API_URL + '/users/active', options).pipe(map(r => r.data.users));
  }

Later on, there was a need to load a milpac information into a User object:

getMilpac(userId: number): Observable<Milpac> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.API_AUTH_HEADER
    });
    const options = { headers: headers };
    return this.http.get<MilpacResult>(this.API_URL + `/user/${userId}/milpac`, options).pipe(map(r => r.data));
  }

My goal now is to load a Milpac object into a User object, within an observable stream.

The final observable result should still be User[] with populated fields from Milpac.

I've heard about mergeMap functions but can't seem to implement them correctly. Any guidance would be appreciated!

Answer №1

To address this issue effectively, it is recommended to handle it on the server side. However, if you must handle it on the client side, you can follow these steps:

  1. Utilize Array.from to separate your users individually.
  2. Apply mergeMap to each user along with its account balance and immediately direct the output back to the user.
  3. Use toArray to convert your users back into an array format.

I have created a simplified example here: https://stackblitz.com/edit/rxjs-6mivga

Keep in mind that this approach works well when your stream completes. If the stream does not complete, the process becomes more complex, but the fundamental mechanism remains unchanged.

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

Using RxJS to merge various HTTP requests into a unified and flattened observable array

Struggling with combining multiple http get requests simultaneously and returning them as a unified, observable array. In my current setup, the method returnNewCars() retrieves Observable<ICar[]> by executing a single http get request. However, in t ...

I'm having trouble getting Remix.run and Chart.js to cooperate, can anyone offer some guidance?

I've encountered a challenge with Remix.run and chart.js (react-chartjs-2) when attempting to display the chart. I followed the documentation and installed the necessary dependencies: react-chartjs-2 and chart.js. Here's the snippet from my pac ...

Even after rigorous type checking, TypeScript continues to throw the ts2571 error when handling an unidentified variable

Consider this scenario: the code snippet below will result in an Object is of type 'unknown'. error: let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Could be anything with the same structure let key = "he ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

What is the use of the mongoose $gt operator in an Express application built with

I am searching for users whose tokens have not yet expired. try { const user = await User.findOne({ resetToken: passwordToken, resetTokenExpiration: { $gt: Date.now() }, _id: userId, }); if (!user) { throw new NotFoundEr ...

Does the class effectively implement the interface even if the method of a member variable has undefined arguments?

Let's take a closer look at my code, which lacks proper descriptions. Here is the interface: interface IModel<T = any> { effects: { [key: string]: (getState: () => T) => void; }; } interface IState { name: string; age: numbe ...

Issue encountered while integrating the angular-fontawesome library in StackBlitz

After trying to add a library, an error keeps popping up on stackblitz. The error message in ~/src/main.ts states that ngcc failed to run on @fortawesome/[email protected]. Link to the Stackblitz project Is anyone else experiencing this issue? ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

Expanding a JSON type in Typescript to accommodate interfaces

Expanding on discussions about passing interfaces to functions expecting JSON types in Typescript, this question delves into the complexities surrounding JSON TypeScript type. The scenario involves a JSONValue type that encompasses various data types like ...

Encountering issues with integrating Sass into Angular 4

Hi there! I recently started a new project in Angular 4 and encountered some issues with the Sass styling. Every time I try to add sass and run the project, I keep getting this error message: body{ h1{ color : red; } } ^ Invalid ...

Expanding one type by utilizing it as an extension of another type

I am looking to create a custom object with predefined "base" properties, as well as additional properties. It is important for me to be able to export the type of this new object using the typeof keyword. I want to avoid having to define an interface for ...

SolidJS does not support reactivity for arrays of objects

I've been scratching my head trying to figure out why this code isn't working as expected. I'm simply updating an object and expecting it to be refreshed in the DOM, but for some reason, that's not happening. The console log confirms th ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Protractor's Page Object returning inaccurate count

I am currently working on writing e2e tests for an Ionic app using Protractor and Cucumber. I have implemented a page object pattern, but I am facing an issue where the call to count() is returning 0, even though I have waited for the elements to be presen ...

Angular: Issue with object instantiation - Unable to assign property

Having trouble populating my array due to instantiation issues. Defined Models: user: User = { firstName: "", lastName: "", address: "" } order: Order = { OrderId: "", User: this.user, TotalPrice: 0, OrderItems: [] } Attempting to populat ...

Getting the string value from an observable to set as the source attribute for an

I am facing an issue with my image service. It requires the user_id to retrieve the id of the user's profile picture, followed by another request to get the JPG image associated with that id. To fetch the image, use this code snippet: <img [src]=" ...

How can I verify the validity of a regular expression in Typescript without encountering a syntax error?

I am facing an issue with my code where I load a set of regular expressions from an external source. My goal is to determine if a given string is a valid regex without causing the application to crash due to a syntax error. Despite trying to use try/catch ...

Is there a way to determine the most recent Typescript target compatibility for every Node version?

When using any version of Node, how can I identify the appropriate Typescript Compiler Option for target that offers the most functionality? I want to eliminate any guesswork. Specify the ECMAScript target version as: "ES3" (default), "ES5", "ES6"/"ES20 ...

Experiencing excessive CPU consumption from Node process while running ng serve command in Angular CLI

I'm having difficulty with a problem where when running any angular app locally, the node process associated with ng serve is using more than 100% of my CPU core. My current setup includes: Angular CLI: 7.3.10 Node: 11.15.0 OS: darwin x64 (Mac OS X ...

Executing a function simultaneously in two separate tabs using Angular

I need to conduct a specific test within my web application that requires opening two separate tabs in my browser and running the application in both tabs simultaneously. My goal is to execute the same function at the exact time in both tabs (for example, ...