Utilizing ConcatMap in conjunction with an internal loop

I am having a coding issue where I need certain requests to run sequentially, but some of the responses are observables. The data is mainly retrieved except for two requests that need to be executed in a loop for each account. I am using concatMap and forkJoin methods to handle this, but now I am stuck on how to extract the data from these observable responses without nested subscriptions...

this.subscriptions.push(
  this.service1
    .subscribeToHouseholdId()
    .pipe(
      concatMap((householdId: number) => {
        return forkJoin([this.service2.getAccounts(householdId), this.service3.getTemplates()]);
      }),
      concatMap(([accountResponse, templates]) => {
        return observableOf(
          accountResponse?.results.map((account) => {
            return forkJoin([
              this.service3.getData1(account.id),
              this.service3.getData2(account.id)
            ]);
          })
        ).pipe(
          map((data) => {
            return [data, accountResponse, templates];
          })
        );
      })
    )
    .subscribe(([data$, accountResponse, templatesResponse]) => {
      const accountResults = accountResponse as IAccount;
      const templates = templatesResponse as ITemplate;

      const templatesData = this.filterTemplatesData(templates);

      accountResults?.results.forEach((account, index) => {
        const { instruction, brokerage } = data$[index];
        const tableData = instruction as IInstruction[];
        const bepData = brokerage as IPlan;
      });
        
    });
);

At the bottom part of the code, 'instruction' and 'brokerage' are observed instead of having the actual data. How can I retrieve the data from these observables efficiently without using nested subscriptions?

Answer №1

It's clear that the key aspect here lies in the code snippet below:

return observableOf(
  accountResponse?.results.map((account) => {
    return forkJoin([
      this.service3.getData1(account.id),
      this.service3.getData2(account.id)
    ]);
   })

The observableOf function (or of function) takes simple data (non-observables) and emits them directly. By mapping your 'results' array to observables (forkJoin returns an observable), they will be treated as simple data, causing the observables to get emitted. Perhaps you should also consider using forkJoin instead of observableOf to subscribe to these observables and emit the result array once everything is complete:

return forkJoin(
  accountResponse?.results.map((account) => {
    return forkJoin([
      this.service3.getData1(account.id),
      this.service3.getData2(account.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

The JSX component cannot be utilized as `ToastContainer`

Check out this Code: import axios from "axios"; import React, { useState, useEffect } from "react"; import { ToastContainer, toast } from "react-toastify"; import loaderIcon from "../../assets/images/loader.gif"; imp ...

Encountered a problem with loading external SCSS files in style.scss using Angular CLI 6 due to issues with postcss-loader and raw-loader in node_modules

ERROR in ./src/styles.scss (./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles.scss) (Emitted value instead of an instance of Error) CssSyntaxError: /Users/src/assets ...

When requesting URLs on the server via Http, they must be in absolute form

Recently, I developed an Angular Universal application using Angular2 where I made a request to the /category service. this.hsService.getCategories(AppConstants.BASE_URL_GET_CATGORIES).subscribe( resp => { if (resp !== null) { console.log(& ...

Delete the option "x" from the kendo combobox

Is there a way to eliminate or hide the clear ("x") action from a Kendo combobox using TypeScript? I have attempted to find a solution through SCSS/CSS, but I have not been successful. Alternatively, I would be fine with preventing the event triggered by ...

Using Angular 2, NodeJS, and Mongoose to send data from an Angular 2 frontend to a NodeJS backend REST API. However, encountering an issue where the Node API logs show that the OPTIONS

I am facing an issue with sending data from my Angular2 frontend API to the backend client, which is built using NodeJS and mongoose. When I inspect the data being sent on the Angular2 client through console.log, I can see that the correct values are being ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Using `it` with accessing class members

When testing whether a specific object/class is correctly wired up, I often utilize it.each to prevent writing repetitive tests. The issue arises when the type of the object doesn't have an index signature, requiring me to cast it to any for it to fun ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

angular2: Comparing Routes without Components to Routes with Empty Paths

As per the latest version of angular2, routes can be declared in two ways: Componentless Route: Setting up URLs without specifying a component Empty path routes: Setting up Components without specifying a URL. Is this accurate? Can someone provide a det ...

Retrieve the template parameter from a generic type

While I have experience extracting string from string[], this particular scenario is proving to be quite challenging: type example<T = boolean> = true; // with just "example", how can I retrieve the template parameter "boolean" in this case? type T ...

What is the process for retrieving a string value from a URL?

Here is the link to my page: http://localhost:4200/#/home/jobmanager/status Can someone help me figure out how to extract the "status" from the URL as a string in TypeScript (.ts file)? For example: this.getJobs("STATUS_HERE"); I need to replace "STATU ...

Getting Angular 2 and Ionic 2 to play nice together: is it worth the effort?

Recently, I attempted to create a glossary app using Ionic 2 and encountered numerous challenges when incorporating the http service. The Angular 2 tutorials had been updated, configuring the mock server proved difficult, and the Ionic 2 documentation offe ...

ExitDecorator in TypeScript

Introduction: In my current setup, I have an object called `Item` that consists of an array of `Group(s)`, with each group containing an array of `User(s)`. The `Item` object exposes various APIs such as `addUser`, `removeUser`, `addGroup`, `removeGroup`, ...

Is there a surefire method to ensure that ChromeDriver in Protractor consistently uses the stable version?

Every time Chrome releases an update, I encounter a recurring issue. Allow me to paint the picture: All browsers are at version 83 of Chrome Chrome announces that version 84 is on its way, but it has not been released yet. A new ChromeDriver 84 is rolled ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

Generate a new Angular2 component on the fly based on information retrieved from an API request

Within my application, I have implemented a dropdown menu featuring 'Statements' that users can select. Upon the selection of a specific statement, an API call is triggered to fetch data on how this information should be displayed, referred to as ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

Can a personalized component be displayed as a tooltip?

I find the existing tooltip design too complicated to work with. Are there any alternatives such as creating a new component to use instead? ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...