Participating in consolidated data

I need to merge data from my trainings-table with my users-table.

The structure of the data is as follows:

 - users
  - key1
     - name
     - trainingIds
         - t_key1
         - t_key3
 - trainings
  - t_key1
     - name
     - description
  - t_key2
     - name
     - description
  - t_key3
     - name
     - description

After researching on Stackoverflow, I came across a helpful solution. However, I encountered an issue mentioned by Romain Bruckert that I was unable to resolve.

This is the code I have so far:

this.visibleUser$ = af.database.list(`${this.path}`)
        .map( users => {
          console.log( users );
          return users.map( user => {
            console.log( user );
            console.log( user.trainingIds );
            user.trainingIds.map( trainingIdsMap => {
              af.database.list(`dev/trainings/${trainingIdsMap.$key}`)
              .map( tr => {
                trainingIdsMap = tr;
              });
            });
            return user
          });
        }) as FirebaseListObservable<any>;

This represents the Firebase data structure:

{
  "trainings" : {
    "-KdGENe4XiCyEowgYGbu" : {
      "description" : "lala beschreibung",
      "name" : "Bring Sally Up Challenge"
    },
    "-KdGGjQtvdLPWZOSHjKP" : {
      "description" : "Beschreibung für liegestütz",
      "name" : "Ligestütze"
    },
    "-KdGH3qNKCWGnW1kebMj" : {
      "active" : false,
      "description" : "Des funktioniert ja wirklich",
      "name" : "Wahnsinn"
    },
    "-KdHSzTb63L9_6qw461X" : {
      "description" : "klettern klettern klettern",
      "name" : "8a Training"
    },
    "-KdI2OXgEO0GnIqDXaDT" : {
      "description" : "Bes",
      "name" : "Test"
    }
  },
  "users" : {
    "8faYwT4xp4SoXzU3HPnc2rIsqyp1" : {
      "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4e464a42476b5c4e49054f4e">[email protected]</a>",
      "trainingIds" : {
        "-KdGH3qNKCWGnW1kebMj" : false,
        "-KdHSzTb63L9_6qw461X" : true
      },
      "username" : "didi"
    },
    "EWt2O16J9MasAwuoi92PQ3h66Bw2" : {
      "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a4aca0a8ad81b8a0a9aeaeefa5a4">[email protected]</a>",
      "username" : "ChrisB"
    }
  }
}

I have followed Clark's suggestion and imported the rxjs map operator, but it did not resolve the issue. The problem appears to be with the list of trainingIds, which are returning as an object instead of an array as expected, as shown in the console logs.

Console log: Stack Overflow Discussion

Any suggestions on how to overcome this challenge?

Answer №1

Here is a solution that works effectively.

To see this code in action, take a look at the live Plunker demo. The console will display users along with their respective trainings.

const visibleUser$ = user$
  // Flatten the array of users to emit them individually.
  .mergeMap(val => val)
  // Get an observable for each user to retrieve their trainings.
  .mergeMap(user => {
    // Array of observables to fetch the trainings for the current user.
    const trainingsArr = user.trainingIds.map(trainingId => getTraining(trainingId));
    // Extract trainings and merge them with the current user.
    return Rx.Observable.from(trainingsArr)
      .mergeAll()
      .toArray()
      .map(userTrainings => Object.assign(user, {trainings: userTrainings}));
  })
  .toArray()

visibleUser$.subscribe(val => console.log(val));

The console output will be:

[{
  key: "key1",
  name: "user1",
  trainingIds: ["t_key1", "t_key3"],
  trainings: [ 
    {
      desc: "Desc 1",
      key: "t_key1",
      name: "Training 1"
    },
    {
      desc: "Desc 3",
      key: "t_key3",
      name: "Training 3"
    }
  ]
},
{
  key: "key2",
  name: "user2",
  // ...
}]

In the Plunkr demo, I have replaced live Firebase calls with observables containing dummy data. Specifically, in my example, you should substitute:

  • user$ with af.database.list(this.path)
  • getTraining(trainingId) with
    af.database.list(dev/trainings/${trainingIdsMap.$key})

If you have any queries regarding the code, feel free to ask.

Just a small note: in your code, instead of using "af.database.list(${this.path})", you can simply use af.database.list(this.path). No need for string interpolation if it's just a variable. :)

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 a React.tsx project be developed as a standalone application?

As a student, I have a question to ask. My school project involves creating a program that performs specific tasks related to boats. We are all most comfortable with React.tsx as the programming language, but we are unsure if it is possible to create a st ...

Error encountered while loading GitHub Pages resource

Currently, I am facing issues while attempting to host an Angular application with Bootstrap 4 on GitHub Pages using angular-cli-ghpages. The URL I am trying to deploy it at is , but I continuously encounter the following error: Failed to load resource: s ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

The complete Angular 2 application fails to load when accessed using a custom domain name

I've been struggling for the past few days trying to solve a strange issue. When I try to access my Angular 2 app using a domain name (example.com), it gets stuck on the loading screen. However, if I try accessing the same app without nginx, it loads ...

How to extract a type from a nested type using TypeScript

I am trying to define a type structure where both a and foo are optional: type Something = { a?: { foo?: { bar: { c: { id: string, countryCode: number, animal: { ... } } } } } } Now I n ...

Using relative URLs in Angular 2 CSS

Struggling in Angular 2 to set a background image for a division using a .css file in the component, but encountering errors due to relative paths. test.component.html <div class="release-bg"></div> test.component.css .release-bg{ b ...

Get the download URL from Firebase Storage and save it into an array within Firestore

I am currently working on a project to upload multiple image files to Firebase Storage and then store their download URLs in a single array within Firestore. uploadImages(name, images) { for (let i = 0; i < images.length; i++) { const file = ...

Yep, identifying InferType optional attributes

Here's an example of a Yup schema I created to fetch entities known as Parcels: export const FindParcelsParamsSchema = Yup.object({ cursor: Yup.number().optional(), pageSize: Yup.number().positive().integer().optional(), }); All fields are option ...

I am experiencing import issues with ts-node/ts-jest and unable to import the necessary modules

I'm having trouble with a syntax error while trying to integrate mdast-util-from-markdown into my Jest tests for a TypeScript project. I am seeking a solution that does not involve using Babel. The code functions properly when using ts-node. Issue: ...

After updating my Angular version from 8 to 9, an error has been thrown stating "It is not possible to assign the value 'undefined' to the template variable 'limit'"

Recently, I made updates to my Angular 8 project by switching it to the newest version of Angular 9. In one of the template's div elements, I declared a variable and everything seemed to be functioning correctly without any errors. To avoid initializi ...

The issue of broken reactivity arises when utilizing defineStore in Pinia with options instead of storeSetup

In my current project, I've implemented two different types of Pinia storage definitions. Here's a condensed look at each: // First Storage Definition using storeSetup export const useStore = defineStore("storeId", () => { const isExpanded: ...

What is the method for defining specific requirements for a generic type's implementation?

I am facing an issue with the following code snippet, where I am trying to restrict the pairing of Chart objects based on correct types for the data and options objects. However, despite my efforts, the TypeScript compiler is not throwing an error in the s ...

There was a problem with Type TS2507: The Type 'typeof Tapable' cannot be used as a constructor function type

After creating my own TypeScript library for shared TS models, I wanted to incorporate it into a couple of other projects I'm working on. Here are the essential parts of the library repository: index.ts: export interface IApp { ... } package.json: ...

"Transform the appearance of the datepicker input field with Material 15's dynamic

I am in need of assistance to change the color to white for the input date and add an underline to a datepicker element <mat-form-field class="date-criteria-select " [floatLabel]="'always'"> <mat-label class=" ...

Enhancing Angular version from 5.2.7 to 5.2.10

After creating an Angular project using an older CLI version, the default installation was Angular version 5.2.7. Now, I am looking to upgrade my application to the latest stable Angular build, which is 5.2.10. One of the main challenges I'm facing i ...

What steps should I take to instruct TypeScript to package a third-party library from the node_modules directory?

I am looking to configure the TypeScript Compiler in such a way that it utilizes node_modules/firebase/firebase.d.ts for typechecking my code, and also includes node_modules/firebase/firebase.js in the files where I import firebase functionalities. Althoug ...

Flashing issues when utilizing the Jquery ui slider within an Angular 2 component

I recently incorporated a jquery-ui slider plugin into an angular 2 component and it's been working well overall, but I have encountered an annoying issue. Whenever the slider is used, there is a flickering effect on the screen. Interestingly, when I ...

Discover the specifics of an element within angular version 6

My goal is to have the details of a course module displayed when it is clicked. However, I am encountering an error with my current code: Cannot read property 'id' of undefined. coursemoduleapi.service.ts getCourseModule(id:number) { return thi ...

Turn off context menus in the Nebular interface when certain conditions are met

Currently, in my Angular 6 project with Nebular, I am facing the following requirement: I need to showcase a nebular context menu on a table row. The context menu should have dynamic enable/disable functionality based on the status of the table column. htt ...

What is the reason for the function to return 'undefined' when the variable already holds the accurate result?

I have created a function that aims to calculate the digital root of a given number. Despite my efforts, I am encountering an issue where this function consistently returns undefined, even though the variable does hold the correct result. Can you help me ...