Merge two RxJS Observables/Subscriptions and loop through their data

Working with Angular (Version 7) and RxJS, I am making two API calls which return observables that I subscribe to.

Now, the challenge is combining these subscriptions as the data from both observables are interdependent. This is necessary to implement certain functions such as a filter that checks if the id received from subscription2 appears in subscription1 before returning something.

Due to the extensive length of my code, I have provided a condensed sample version with key points marked by comments:

getSomething(){
    /**
     * anIdFromSubscriptionTwo: An essential id required from subscription2
     */
    const subscription1 = this.service.getSomeStuff().subscription((someStuff) => {
        this.someStuff = stuff;
        this.someStuff.forEach((stuff) => {
            if(stuff.someProperty !== null && stuff.id === anIdFromSubscriptionTwo){
                ...
            }
        });
    } 

    /**
     * aIdFromSubscriptionOne: Id of type string obtained within forEach loop of subscription1
     * aTypeFromSubscriptionOne: Type of string retrieved within forEach loop of subscription1
     */
    const subscription2 = this.service.getSomeOtherStuff(aIdFromSubscriptionOne: string, aTypeFromSubscriptionOne: string).subscription((someOtherStuff) => {
        this.someOtherStuff = someOtherStuff;
        this.someOtherStuff.forEach(() => {
            // Sole if statement needed after merging the two subscriptions
            if(subscription1.stuff.someProperty !== null && subscription1.stuff.id === someOtherStuff.id){
                const properties: Image = {
                    id: // id needed from subscription1
                    class: // class required from subscription1
                    type: // type needed from subscription2
                    ref: // reference to image URL from subscription2
                    ...
                }
            }
        })  
    });
}

How can I effectively combine these two subscriptions to access their data in my forEach loop for comparison or general manipulation?

Answer №1

Utilize switchMap to prevent nested subscriptions

import { switchMap } from 'rxjs/operators';


  this.service.getSomeData().pipe(switchMap((someData) => {
        this.someData = someData;

      this.service.getAdditionalData(id: string, type: string)
       ).subscribe((additionalData) => {
        this.additionalData = additionalData;
        this.additionalData.forEach(() => {
        // perform a loop here on someData to check for matching data in additionalData
          this.someData.forEach((data) => {
             if(data.property !== null && data.id === additionalData.id){
               const properties: Image = {
                id: // retrieve an id from the first subscription
                class: // obtain a class from the first subscription
                type: // fetch a type from the second subscription
                ref: // get a reference to the image URL from the second subscription
                ...
               }
             }
           });  
         }); 
      });   
  });

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

Definition in TypeScript: specify a type or interface containing a field with an unidentified name

Looking to define an interface for a team object: export interface Team{ memberUid?: { mail: string name: string photoURL: string } startDate: Timestamp endDate: Timestamp agenda: Array<{ date: Date | Timestamp title: strin ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

npm is unable to install a forked git repository in its current state

Attempting to install a customized version of ng2-smart-table on my application, but npm seems to be struggling with the process. I've experimented with various commands such as npm install git+http://github.com/myusername/ng2-smart-table.git npm i ...

Issue with Angular4 select in dropdown not able to trigger onChange event

I am new to working with Angular 4 and I am currently in the process of building something. In my project, I have multiple components, one of which contains the following HTML code: <div class="row" style="border:1px solid black;"> <br> <d ...

Issues with try_files directive in nginx.conf file

I have a situation where I am working on an angular 2 app, using nginx and docker. However, whenever I reload a page with /site in the URL, it gives me a 404 error. Here is my current server block configuration: server { listen 0.0.0.0:80; listen [::]:80; ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Placing an image on the chosen option of a <mat-select> using Angular Material

I have incorporated Angular Material into my Angular 2 project, and I am trying to insert a static image (HTML element) in the selected value of mat-select. Unfortunately, I have been unable to find a solution for this issue. Is there anyone who can ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

Launch a fresh window in Angular application without the need for a complete restart

How can I open a new window in Angular while passing values in the route to call an endpoint without causing the entire application to reload? It feels like such a hassle just to display a simple HTML page. Is there a better way to achieve this? ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Issue: The function "generateActiveToken" is not recognized as a function

I encountered an issue in my Node.js project and I'm unsure about the root cause of this error. Within the config folder, there is a file named generateToken.js which contains the following code snippet: const jwt = require('jsonwebtoken'); ...

Methods for defining a variable in React with Typescript without encountering the "Index signature is missing in type" issue

I am facing an issue while trying to declare a variable 'reports' and assigning it to an array of arrays containing string and number types. The problem arises when I try to assign it, resulting in errors. ... // Retrieving data from an API let ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

Using Angular and Spring to Add Captcha to Your Web Application

Is there a way to incorporate captcha into an Angular application with Java-Spring Boot as the backend without using Google's reCaptcha library? The server hosting the application does not have Internet access. At the moment, I am sending a captcha n ...

Displaying a pair of items side by side using Angular's ngFor

I've encountered an issue with my code related to displaying a 4 by 8 grid using the ngFor command. Below is the snippet of the code in question: <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)"> <ng-cont ...

Angular 9 - Auto-adjust the height of the text box as the user types, returning to its original size when no longer in focus

I need a solution where an input field's height adjusts to display the user's entry, then returns to normal size when they click away. It should function similar to this example image: https://i.stack.imgur.com/yKcik.png Once the user enters th ...

Issues encountered when integrating ag-grid-react with typescript

Despite extensive searching, I am unable to find any examples of utilizing ag-grid-react with TypeScript. The ag-grid-react project does have TypeScript typing available. In my React app, I have installed ag-grid-react: npm i --save ag-grid ag-grid-react ...

Azure Static Web App does not retrieve the connection string value from environment.prod.ts

After deploying my Angular App to Azure as a Static Web App, everything seemed to be running smoothly. However, I encountered an issue with the file "environment.prod.ts" in the environments folder within my app that contains the following code: export co ...

Enhancing the session object with new properties

I am attempting to include extra properties in the session object req.session.confirmationCode = confirmationCode; However, I encounter an error stating that the property confirmationCode does not exist Property 'confirmationCode' does not exist ...