Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows:

const logs: number[] = [1, 2, 3, 4];
const url = 'http://some-url-here.com';

const pipeline = from(logs).pipe(
  switchMap(logId =>
    this.callEndpoint(url, logId).pipe(map(response => response.data)),
  ),
);

const res = await pipeline.toPromise();
console.log(res);



// The actual function utilizes nestJS http service to reach a URL
callEndpoint(url: string, logId: number) {
  const result = Math.random() * 1000;
  console.log(`result in callEndpoint: ${result}`);
  return of({ data: result });
}

A preview of the code's output can be seen below:

result in callEndpoint: 586.773956063481
result in callEndpoint: 842.136341622411
result in callEndpoint: 964.0849490798163
result in callEndpoint: 598.7596176858414
598.7596176858414

The final number represents the value stored in res.

Is there a way to consolidate all the successful endpoint calls' results into a single array within the variable res?

Answer №1

For sending all requests simultaneously, use the forkJoin method. If you prefer to send requests sequentially and gather the results in an array, then use concat along with toArray. It's advisable to include error handling using catchError to ensure that the observable does not produce any errors.

const getData = (logId) => this.callEndpoint(url, logId).pipe(
  map(response => response.data),
  catchError(error => of(null))
)
const requests = logs.map(logId => getData(logId));

// for parallel requests
forkJoin(requests).subscribe(res => console.log(res));

// for sequential requests
concat(...requests).pipe(toArray()).subscribe(res => console.log(res));

The resulting array stored in res may contain null values if a request fails. For example, if the second request fails, the array might look like:

[586.773956063481, null, 964.0849490798163, 598.7596176858414]

Answer №2

Utilize the function toArray() to gather all emissions and emit them as a single array once the source observable is completed.

const pipeline = from(logs).pipe(
  switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response.data)),
  toArray(),
);

However, it seems that using switchMap in this scenario may not be ideal. Since the source observable, from(), immediately emits all items from logs, switchMap will only remain subscribed to the last item. Consider utilizing concatMap instead.

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

Incorporating HTML and JavaScript into TypeScript: How to Embed a Shopify Buy Button in a .tsx document

I am currently looking to integrate Shopify with my personal website. My frontend is built using React (NextJS with TypeScript). The embed code for the Shopify buy button consists of an HTML div tag wrapping JavaScript. I am wondering how I can effectivel ...

Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process. According to the Webpack .md file: exclude Type: String|RegExp|Array Default: undefined This setting is used to spe ...

Creating an Inner Join Query Using TypeORM's QueryBuilder: A Step-by-Step Guide

Hello there! I'm new to TypeORM and haven't had much experience with ORM. I'm finding it a bit challenging to grasp the documentation and examples available online. My main goal is to utilize the TypeORM QueryBuilder in order to create this ...

Unable to locate the specified environment variable in the current nest

Currently, I am referring to the official documentation on the NestJs website that provides a guide on using config files: https://docs.nestjs.com/techniques/configuration Below is the code snippet I am working with: app.module import { Module } from &ap ...

Typescript interface design for nested objects in a hierarchical structure

When data is received from the server in JSON format, it typically looks like the example below (details have been modified): { "apple": { "fruitName": "apple", "types": { "greenApple": { ...

How can we access child components in vanilla JavaScript without using ng2's @ViewChild or @ContentChild decorators?

Recently, I delved into the world of using ViewChildren and ContentChildren in Angular 2. It got me thinking - can these be implemented in ES6 without TypeScript annotations? The TypeScript syntax, according to the official documentation, looks something ...

Combining functions does not result in a callable function, even when the parameters fulfill the constraints of each individual function

I have encountered an issue while trying to compile a Typescript snippet: function foo(v: string) { return 'foo'; } function bar(v: string | number) { return 'bar'; } const notCallable: typeof foo | typeof bar = function() {} as any; ...

Tips for using the "distinct" RxJS operator effectively in Angular 2

Is there a method to clear the cache of distinct()? Sometimes, when I reset this.messages=[], I would like to clear the cache. Instead of finding a proper solution, I have resorted to a workaround where I increase distinctCount. ngOnInit() { let cach ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

The collaboration of React hooks, typescript, mongoose, express, and socket.io in perfect harmony

I am currently working on setting up a frontend React app to communicate with a NodeJS Express API using socket.io import React, { useEffect, useState } from "react"; import io from "socket.io-client"; const socket = io("http://lo ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

When using RXJS, the method BehaviorSubject.next() does not automatically notify subscribers

In my project, I have a service set up like this: @Injectable({ providedIn: 'root' }) export class MyService { private mySubject = new BehaviorSubject({}); public currentData = this.mySubject.asObservable(); updateData(data: any) { ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...