Tips for managing an array of observable items

In my current project, I am working with an Angular application that receives a collection from Firebase (Observable<any[]>). For each element in this collection, I need to create a new object by combining the original value with information from another Firebase collection.

 getLoans(loanStatus: boolean){
return this.afs.collection<any>('loans', ref => ref.where('returned', '==', loanStatus)).valueChanges()
  .pipe(
    map(loans => loans.map(loan => ({...loan, userCompleteInfo: this.fetchUserInfo(loan.user).subscribe(data => {return data;})}))),
    tap(data => console.log(data))
  );

   fetchUserInfo(userId: string){
    console.log(userId);
    try{
      return this.afs.doc<any>('users/' + userId).valueChanges().pipe(
        tap(user => console.log(user))
      );
    }
    catch(error) {
    console.log(error);
    }
  }

I have experimented with various iterations of the code above but haven't been successful. The getLoan() method needs to return an observable<any[]>. Thank you for your assistance,

Answer №1

If you want to streamline the handling of inner subscriptions, consider using a higher order operator such as switchMap. Additionally, make use of combineLatest to merge all inner observables into one.

fetchLoans(isLoanState: boolean){
  // retrieve your collection
  return this.afs.collection<any>('loans', ref => ref.where('returned', '==', isLoanState)).valueChanges()
  .pipe(
    // switchMap to combineLatest of array mapped into 
    // inner observables that map into the complete object
    switchMap(l => combineLatest(
      ...l.map(y => this.getUserDetails(y.user).pipe(
        map(completeUser => ({...y, completeUser}))
      ))
    ))
  )
);

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

Tips for enabling users to import from subdirectories within my NPM package

Is there a way to allow users to import from subfolders of my TypeScript NPM package? For instance, if the TypeScript code is structured like this: - lib - src - server - react Users should be able to import from the subfolders as package-name/react, ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...

Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items. The final JSON output should be sorted by the attribute 'name&apos ...

Is there a way to simulate an imported dependency using express?

Currently, I am conducting unit tests on an express function that utilizes an import (stripe) which I aim to mock. Is there a way to effectively mock this import while still using the express function? The dilemma arises from the fact that it is a global i ...

Exploring an array in React using typescript

I have a persistent data structure that I'm serving from the API route of my Next.js project. It consists of an array of objects with the following properties: export interface Case { id: string; title: string; participants: string[]; courtDat ...

Integrating Angular 2 with Java functionalities and JSP

Starting my journey with the Angular 2 framework, I recently dove into working with it. As I delved deeper, many questions began to surface. My initial step was creating an Angular project using the Angular CLI, which went smoothly. However, when I attem ...

A step-by-step guide on retrieving the present date and time using TypeScript

Details This is my first time creating a VSCode extension using TypeScript, and I am having trouble displaying the current date/time in an information message. My Attempts I have searched through VSCode key bindings for any references to date/time, as w ...

Is there a way for me to steer clear of having to rely on the Elvis Operator?

Throughout my journey building my Angular 2 website, I've found the Elvis Operator to be a crucial element that makes everything possible. It seems like every task I undertake involves mastering how to apply it correctly in every instance where data i ...

Tips for implementing a reusable component in Angular 2

Within my module.ts file, @NgModule({ imports: [ BrowserModule, RouterModule.forRoot([ { path: '', component:AppComponent}, { path: 'login', component:AppComponent} ]) ], declarations: [ AppComponent,Mainapp ...

Transforming Typescript Strings into ##,## Format

As I've been using a method to convert strings into ##,## format, I can't help but wonder if there's an easier way to achieve the same result. Any suggestions? return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, max ...

Leverage VueJS and VueX to seamlessly integrate firebase 9 functions within my application

I am currently in the process of developing a blog application using Firebase version 9, VueJs version 3, and VueX. All functionalities such as user registration and authentication are working smoothly. However, I encountered an error when attempting to a ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

Is it possible to utilize useEffect for verifying the existence of the user token within the localStorage?

I am in the process of developing a web application that requires authentication. I am wondering if it is effective to create a private route by adding a condition in the useEffect hook of one of my pages. The idea is to check if a token is present before ...

Incorporating Highcharts JS into a mobile app for a seamless data

After deciding to create an Android application that mirrors some features of a webpage, such as weather meteograms built with Highcharts, I delved into the process. Considering my use of Angular 2, I thought utilizing Angular 2 + NativeScript would be th ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...

Receiving an error message "Cannot read property 'X' of undefined" when invoking a sibling method

I'm completely new to Angular and trying to understand how events work within this framework. Here is my Parent Template setup: <child1 (myEvent)="child2.testMethod()"></child1> <child2 #child2 *ngIf="show"></child2> When I ...

Troubleshooting: Prettier Extension Compatibility Issue in VS Code with Create-React-App and Typescript Template

I'm currently in the process of setting up my application using the Create-React-App startup package with the TypeScript template. Everything goes smoothly during the initial installation. However, when I attempt to use the Prettier Code Formatter ext ...

Encountering: Server Failure TypeError: Unable to access attributes of an undefined element (accessing 'length') within NextJS

Why is the component rendering correctly but the browser console is throwing an error? How can I resolve this issue? in firebase.js import * as firebase from "firebase/app"; const firebaseConfig = { apiKey: "my api code", authDomain: "mywebs ...

Issue with TranslateModule Configuration malfunctioning

I have put together a file specifically for managing ngx-translate configuration: import { Http } from '@angular/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModu ...

A single network request is made for every subscription

When making a post request using HTTPClient and subscribing to the returned observable, I am encountering strange behavior where each subscription triggers a new post request. So, if I subscribe to the observable 5 times, I end up with 5 separate post requ ...