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

Can you clarify the significance of the "1" in this particular Typescript code snippet?

Can anyone provide some insight into the purpose of this '1' in the following TS code snippet? decryptPassPhrase() { this.$encrypt.setPrivateKey(privateKey); this.decryptedPassPhrase = this.$encrypt.decrypt(this.encryptedPassPhrase); ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Angular's observable function is not providing a complete response

In my Angular component, I have a function that is called from a template. This function returns an Observable of type string, but unfortunately it only returns the `data` variable. How can I modify it to return `dateNew[0] + " de " + data + " de "+ dateNe ...

What is the best way to structure YAML information in Angular version 14?

I am developing an Angular 14 Application where I have received YAML data in the API Response. I want to display it on my frontend, but the pre tag only shows plain text without any formatting, color, or line numbers similar to other websites I've see ...

In Next.js, the switch button remains in the same state even after the page is refreshed

Is there a solution for this issue? I am currently developing a switch button for a configuration page. The problem arises when I toggle the switch from active to maintenance mode, save it successfully, but upon refreshing the page, the switch reverts back ...

Ensure that the dropdown remains open at all times when using the angular2-multiselect-dropdown package

I am currently implementing the angular2-multiselect-dropdown in my Angular application. This dropdown is being used within a popup. What I am trying to achieve is that when a button is clicked, the popup should display the dropdown in an open mode witho ...

Contrasting the utilization of `typeof` with a constant and `enum` in TypeScript

Can you explain the distinction between using typeof with a constant and an enum in TypeScript? For example: const TYPE_A = 'a' const TYPE_B = 'b' type MyType = | typeof TYPE_A | typeof TYPE_B type Result = { name: string type ...

Is it possible to conceal my Sticky Div in MUI5 once I've scrolled to the bottom of the parent div?

Sample link to see the demonstration: https://stackblitz.com/edit/react-5xt9r5?file=demo.tsx I am looking for a way to conceal a fixed div once I reach the bottom of its parent container while scrolling down. Below is a snippet illustrating how I struct ...

Encountering the issue: "Error: The mat-form-field must include a MatFormField

Working on an Angular form, attempting to validate a reactive form with Material design template. Encountering an error when trying to use ngIf condition for validation in the textbox: Error: ERROR Error: mat-form-field must contain a MatFormFieldContr ...

Upon receiving the API response, my Angular webpage is failing to redirect to a different page

After executing my code in TypeScript, I encountered an issue with the updateProduct method calling the API to update a product based on form values. The update functionality works fine, but afterwards, I am receiving the following error: error: SyntaxErr ...

Why Mixin Class inference is not supported in Typescript

I encountered an issue in my code: The error message 'Property 'debug' does not exist on type 'HardToDebugUser'.' was displayed. It seems like Typescript failed to infer the mixin class correctly. Can you please explain this t ...

Setting up a global CSS and SASS stylesheet for webpack, TypeScript, Phaser, and Angular: A step-by-step guide

A manual configuration has been set up to accommodate all the technologies mentioned in the title (webpack, typescript, phaser, and angular). While it works perfectly for angular component stylesheets, there seems to be an issue with including a global st ...

Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task. My goal is to make two parallel requests an ...

Guide to Re-rendering a component inside the +layout.svelte

Can you provide guidance on how to update a component in +layout.svelte whenever the userType changes? I would like to toggle between a login and logout state in my navbar, where the state is dependent on currentUserType. I have a store for currentUserTyp ...

Implement a call feature using ReactJS

My service method involves making a PUT call to an API with an ID parameter. However, I am facing issues with hitting the .put URL. Can someone please verify if this is the correct approach? ENDPOINTS = { SAMPLE: "/sample", }; Below is my ...

The use of aliases is not supported by a published node module

I have a project built using create-react-app and it's utilizing react-app-rewired/react-scripts-ts. Within my tsconfig file, I've configured it as follows: baseUrl: "src", paths: { "src/*": "./*" } In many files within this project, the pa ...

Auth.logout() callback in AngularFire 2

As I attempt to log out and then navigate to a login URL, I encounter an issue with the authguard preventing logged-in users from accessing it. Due to the asynchronous nature of the operation, clicking the method event twice seems to be necessary for it to ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Ways to make an element disappear when clicking outside of it in Angular 7 or with CSS

After entering text into an input field and pressing the space key, a div called 'showit' will be displayed. However, I want this div to hide when clicking outside of it. See the code below for reference: home.component.html <input type="tex ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...