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 utilizing the onClick handler when mapping through items in React

Currently, I am a student learning about react. During the course of working on a project, I encountered a problem that left me with a question. {pages.map((page, idx) => ( <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}> < ...

Incorporating Vaadin components into an Angular2-seed project

Hi there, I've been encountering an issue while trying to integrate Vaadin elements into my Angular2 seed project. The Vaadin team has recommended that I upgrade the systemjs.config.js file by specifying the path names for Vaadin elements like this: ...

How can I access DOM elements in Angular using a function similar to the `link` function?

One way to utilize the link attribute on Angular 2 directives is by setting callbacks that can transform the DOM. A practical example of this is crafting directives for D3.js graphs, showcased in this pen: The link attribute: When it comes to manipula ...

When a large object changes value in Firebase, does it transfer only the delta change in internet bandwidth?

Hello, I am working with a node that contains an array of 1000 nodes, totaling around 60KB in size. rootRef.on('value', function (snapshot){ //callback every changes props , full list obj }); I would like to know: - When a node in ...

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

The css property of *ngContainerOutlet is ineffective when applied to an ng-component with encapsulation

When I utilize *ngContainerOutlet to dynamically insert components, it wraps the component's template within an ng-component tag which causes my CSS styles to become ineffective. For example: <div class="my-class"> <ng-container *ngComp ...

Angular allows you to dynamically alter the background color of the currently active mat-tab using code

Greetings, I have an Angular page that consists of tabs created with Mat Tab. I successfully changed the background color of the active tab using SCSS and this is the code I used: ::ng-deep .mat-tab-label.mat-tab-label-active { background-color: var(--user ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

Programmatically click a button from the library by triggering a click on its outer div using Angular

Currently, I'm just starting out with Angular. I've been using the @abacritt/angularx-social-login package and noticed that the Google button it provides is only an icon. I'd like to customize its appearance by placing the icon inside a div ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

The Recoil Nexus encountered an error: the element type provided is not valid. It should be a string for built-in components or a class/function for composite components, but an object was

Encountered the following error message: Error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. at ReactDOMServerRenderer.render ... This issue arose when integra ...

Failed to interpret Firebase ID token decoding

My approach involves restricting my API to only logged-in users by sending a Firebase token and attempting to verify it on the server-side, following Google's guidelines precisely as mentioned here. However, I encounter an exception that reads: Fire ...

Angular: Changing the class of a parent element dynamically while iterating through a list with ngFor

I have a unique challenge where I am trying to style a checkbox as a button by placing it inside its label. <label> <input type="checkbox" name="..."> </label> My goal is to toggle the parent label's class based on whether the che ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

After successfully logging in with the angular2-token package, the Rails 4 API is responding with a 401 unauthorized error

In my current setup, I have a Rails 4 API with the gem Devise Token Auth hosted separately from my Angular 2 frontend application. To handle cross-origin requests, I have configured Rack CORS. Using Angular2-token on my front end, I can successfully sign u ...

A guide on applying color from an API response to the border-color property in an Angular application

When I fetch categoryColor from the API Response, I set border-left: 3px solid {{element.categoryColor}} in inline style. Everything is functioning correctly with no development issues; however, in Visual Studio, the file name appears red as shown in the i ...