Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection:

{
city: new york,
country: usa
addedBy: feibf78UYV3e43 // This is the USER ID from the User Collection.
}

What I need to achieve is to fetch the user information for each document in my collection, however, the user data is being retrieved as Observable. How can I accomplish this task? The desired object structure should look like this:

{
city: new york,
country: usa
addedBy: feibf78UYV3e43 // This is the USER ID from the User Collection.
addedByProfile: {
    firstName: John,
    lastName: Doe,
    age: 34
  }
}

I attempted creating two subscriptions but encountered issues with it.

Below is a snippet of my basic code without the secondary query:

getAllIncome() {
        return this.incomeService.getAllIncomeShops().subscribe(
            snaps => {
                const incomeShops = snaps.map(snap => {
                    // The call to the UserService was intended here to retrieve the user information using the getUser() method by passing the UID. However, subscribing to it caused conflicts.
                    return {
                        id: snap.payload.doc.id,
                        ...snap.payload.doc.data()
                    } as IncomeShop;
                });
                this.showLoader = false;
                this.dataSource = new MatTableDataSource(incomeShops);
                this.dataSource.sort = this.sort;
                this.dataSource.paginator = this.paginator;
            }
        );
    }

Answer №1

Here is a potential solution:

dataWithUser =[];
this.incomeService.getAllIncomeShops()
 .pipe(
      mergeMap(datas => {
        return datas.map(data => {
          return zip(of(data), this.userService.getUser(data.addedBy));
        });
      }),
      mergeAll()
    )
    .subscribe(([data, user]) => {
      dataWithUser = [...dataWithUser, { ...data, addedByProfile: user }];
    });

An issue to note is that the Observable emits each item of the array individually. Thus, we need to gather them all into an array as shown in the code snippet below:

dataWithUser = [...dataWithUser, { ...data, addedByProfile: user }];

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

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Ensure the clarity tabs labels have the padding-left CSS property added

In my project, there are 2 clarity tabs (you can view the StackBlitz reference here). I want to apply the padding-left property specifically to Tab1 (the tab label itself, not the content) in order to create some space around it. Through Chrome Dev Tools, ...

Invoking a C# class file using Typescript

Incorporating TypeScript and Kendo Grid into my project, I am seeking guidance on how to invoke a method within a C# class object (specifically the ProcessData method in the Utility.cs object) from TypeScript. Can someone please advise me on how to accom ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

When incorporating FontAwesome 6 into Angular 18, an error might arise stating, "Unable to associate 'spin' as it is not a recognized attribute of 'fa-icon'."

LAST UPDATE: https://github.com/FortAwesome/angular-fontawesome/blob/main/docs/upgrading/0.14.0-0.15.0.md Confirmed not a bug, it's deprecated. UPDATE - I believe it may be a bug. The version of Font Awesome on one machine is 0.14, while the non-wor ...

I'm encountering an issue with my launch.json file where an error is being triggered on the line that contains "program": "${workspaceFolder}\serve". What could be causing this error?

Whenever I attempt to start the debugger for my Angular application, I encounter the following error message: "Attribute 'program' does not exist ('C:\repos\recipes\serve') I have already attempted to remove the pre-exi ...

How to implement Dragula and Angular to enable draggable elements to be dropped in any position within their container?

I am in the process of developing a web application using Angular, which incorporates dragula. While the current drag and drop functionality works well for moving items within a designated "bag", I am seeking to enhance it with more advanced features. Is ...

Tips for automatically scrolling to the bottom of an element in NgFor when adding new elements

import { Component, Input, AfterViewInit, ViewChild } from '@angular/core'; @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1> <div #commentDetailWrapper style="height: 100px; border: 1px solid; w ...

Using Typescript with React functional components: the proper way to invoke a child method from a parent function

My current setup is quite simple: <Page> <Modal> <Form /> </Modal> </Page> All components mentioned are functional components. Within <Modal />, there is a close function defined like this: const close = () => ...

Error: React - Unable to access the 'lazy' property because it is undefined

I used a helpful guide on the webpack website to incorporate TypeScript into my existing React App. However, upon launching the app, an error message pops up saying: TypeError: Cannot read property 'lazy' of undefined The version of React being ...

Importing dynamically into Ionic 2 from locations other than the "node_modules" directory

I've recently reviewed the documentation for ModuleResolution in TypeScript on this page: https://www.typescriptlang.org/docs/handbook/module-resolution.html#node My understanding is that all files I wish to import must reside within the node_modules ...

Build a new datatable within an Angular component

Currently, I am working on an Angular 2 application where I have a module named Home with a component of the same name. HomeModule.ts: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ...

Error message: "Unable to locate HTML container when trying to create a child element in am

Whenever I navigate away from this page and then come back, the chart does not load. Instead, it displays an error message saying html container not found at createChild https://i.sstatic.net/Y7jVN.png However, if I refresh the page, the chart will appear ...

The Jest worker has run into 4 child process errors, surpassing the maximum retry threshold

I am a newcomer to Vue and Jest testing, and I keep encountering this error when running a specific test. While I understand that this is a common issue, I am struggling to pinpoint the exact cause of the problem. Here is the error message: Test suite fa ...

Incorporating PrimeNG into your Bootstrap 4 projects

Exploring various UI libraries for a new Angular 2 project has been an interesting journey. From Ng-Bootstrap and Material to PrimeNG, each library has its own strengths and weaknesses. Currently, I find that PrimeNG offers a wider range of components comp ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...

When implementing a TypeScript interface, there is no method parameter checking performed

interface IConverter { convert(value: number): string } class Converter implements IConverter { convert(): string { // no error? return ''; } } const v1: IConverter = new Converter(); const v2: Converter = new Converter(); ...

A guide on creating a function that can detect if an object is not iterable and then throw an error

Exploration Uncomfortable type definition at the library: declare type Extension = { extension: Extension; } | readonly Extension[]; Type-validation function export function isIterable(x: any): x is Iterable<unknown> { return Symbol.iterator ...

Phaser3 encountering issues while loading files from Multiatlas

Attempting to utilize the multiatlas functionality in Phaser alongside TexturePacker. Encountering this issue: VM32201:1 GET http://localhost:8080/bg-sd.json 404 (Not Found) Texture.js:250 Texture.frame missing: 1/1.png The JSON file can actually be fou ...