Tips for gathering information from numerous inquiries

In my coding project, I have a function that creates multiple requests:

fetchData(): Array<Observable<AxiosResponse<Data>>> {
    const data = [];
    for (let i = 1; i <= end; i++) {
      data.push(
        this.http.get<Data>(
          generateUrl(i),
        ),
      );
    }
    return data;
  }

Additionally, there is a controller function involved:

@Get()
retrieveData() {
    return this.appService.fetchData().forEach(x => {
      x.subscribe(y => {
        // the goal here is to aggregate and merge the data from each request into a single JSON response
      });
    });
  }

I am currently seeking advice on how to effectively combine all the data retrieved from each individual request in the controller method and output it as a unified JSON object. Any suggestions?

If I attempt the following approach:

  @Get()
  retrieveData() {
    const mergedData = [];
    return this.appService.fetchData().forEach(x => {
      x.subscribe(y => {
        mergedData.push(...y.data);
      });
      return mergedData;
    });
  }

I quickly realized that this method will not succeed since return mergedData would execute prior to the actual completion of .subscribe(...)

The structure of y.data consists of an array of objects such as:

[
 {key:"xyz", value:123 },
 {key:"abc", value:666 }
]

Answer №1

If you want to improve your handling, try using rxjs operators.

import { Observable, range } from 'rxjs';
import { concatMap, toArray } from 'rxjs/operators';

const source: Observable<Data[]> = range(1, end)
  .pipe(
    concatMap((i: number) => this.http.get<Data>(getUrl(i))),
    toArray()
  );

You can then subscribe to the source like this:

source.subscribe((data: Data[]) => {
  // Manipulate data here
});

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

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

Looping through a detailed JSON array filled with objects to extract just a pair of items is essential. I aim to achieve this efficiently by utilizing LOD

Looking at this intricate JSON object... Here's a snippet of the code: entity: [{entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}] 0: {entityName: "Nrm", page: 0, p ...

The comprehensive guide to using ambient enum types in an exhaustive switch statement

Here is a function that maps a place to an emoji: function mapPlaceToEmoji(place: Place): string { switch (place) { case Place.FIRST: return ' ...

The result of chaining methods is a generic object return type

My goal is to achieve the following: let result = loader .add<number>(1) .add<string>("hello") .add<boolean>(true) .run(); I am seeking a method to create the hypothetical loader object in a way that automatically deter ...

Using React Router DOM's History Object in Typescript Triggers an Error

I am encountering an issue with a stateless component that receives the History object from react-router-dom and passes it down to a stateful component through props. Typescript is raising an error when trying to pass the history object as a prop. Below a ...

Transforming an established Angular application into a Progressive Web App

What steps do I need to take in my command line to transform my Angular project into a progressive web app (PWA) similar to react-pwa? ...

How can I correctly modify a specific column in nestjs?

I am looking for a way to store the token that is generated in the user's confirmed email column. This token is included in the confirmation link that will be sent to the user, and upon clicking on the link, I need to check if it matches the token sto ...

Converting JSON Data to CSS Styles in Angular

Currently facing a challenge that has left me a bit stumped... I'm currently developing an Angular application that requires certain fields to be colored based on values stored in an XML file on the server. These colors are configured through an exter ...

What is the best way to redirect to a different page within a function using "react-router-dom" version "^6.21.1"?

Having trouble redirecting to another page and unable to use useNavigate() inside the function as it's not a component. Redirect function also doesn't seem to be working. How can I achieve the redirection? import { redirect, useNavigate } from &q ...

Tips on utilizing JavaScript to retrieve all HTML elements that have text within them, then eliminating the designated element and its descendants

Simply put, I am looking to extract all the text-containing elements from the HTML and exclude specific elements like 'pre' or 'script' tags along with their children. I came across information suggesting that querySelectorAll is n ...

Send an API request using an Angular interceptor before making another call

Within my application, there are multiple forms that generate JSON objects with varying structures, including nested objects and arrays at different levels. These forms also support file uploads, storing URLs for downloading, names, and other information w ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

Loop through a collection of map instances in TypeScript

In my TypeScript code, I am making a call to an API method in a Java class that returns a list of maps. The TypeScript file includes the code snippet below. When attempting to retrieve data from dataBody, it displays as [Object Object]. I need assistance ...

Using Typescript in React to render font colors with specific styling

Attempting to utilize a variable to set the font color within a react component, encountering an error with my <span>: Type '{ style: "color:yellow"; }' is not assignable to type 'HTMLProps<HTMLSpanElement>' The use of yel ...

Steps for developing a versatile function Component

Can I create generic function components? I thought that the following example would work: type MyComponentProps<T> = T & { component: ComponentType<T>, primary?: boolean, size?: 'S' | 'M' | 'L' ...

Error: Identifier 'LibraryManagedAttributes' is already in use

I am facing a similar issue to: React typescript (2312,14): Duplicate identifier 'LibraryManagedAttributes' and TypeScript error: Duplicate identifier 'LibraryManagedAttributes' Despite upgrading to the latest node/npm/yarn/typescript v ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...