What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. These values will then be inserted into the original document before returning the updated collection.

Let's consider an object called ball with the properties:

interface Ball: {
  uid: string; 
  color: string;
}

And an object player with the properties:

interface Player: {
  uid: string;
  correspondingBall: ball;
}

In the Firestore collection, I store documents of type Player with IDs referencing the respective balls they correspond to. Now, I want to access the player collection:

getRecentPlayers(): Observable<Player[]> {
    const players: AngularFirestoreCollection<any> = this.angularFirestore.collection<Player>('players');
    return players ? players.snapshotChanges().pipe(
      map(players => {
        return players.map(player => {
          const data = player.payload.doc.data() as Player;
          const correspondingBall: AngularFirestoreDocument<Ball> = this.angularFirestore.doc('balls/' + data.correspondingBall);
          correspondingBall ? correspondingBall.snapshotChanges().pipe(
            map(ball => {
              const data = ball.payload.data() as Ball;
              return data;
            })
          ) : null;
          return {...data, correspondingBall}
        })
      })
    ) : null;
  }

However, my current approach is not working as expected. Can anyone provide guidance on how to resolve this issue? Thank you!

Answer №1

Typically, the approach involves making a consultation (which returns an array of values), using a switchMap, creating an array of observables, performing a forkJoin operation, and then mapping with an index to incorporate new properties. I prefer a straightforward method utilizing simple get requests in my code.

getPlayers().pipe(
  switchMap(players=>{
    //players is an array containing player objects
    //create an array of observables from the players 
    const obs=players.map(player=>getBall(player.ballId))
    //a switchMap should return an observable, so we use forkJoin
    return forkjoin(obs).pipe(
       //transforming the result, which is an array,
       //with the values obtained from getBall(1), getBall(2)..
       map((ball,index)=>{
          //combine the properties of players[index] with the ball data
          return {...players[index],..ball}
       })
    )
  }
)).subscribe(res=>console.log(res))

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

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

The Angular Observable continues to show an array instead of a single string value

The project I am working on is a bit disorganized, so I will try to explain it as simply as possible. For context, the technologies being used include Angular, Spring, and Maven. However, I believe the only relevant part is Angular. My goal is to make a c ...

Is it possible to draw parallels between Java Callable and Angular Observable (RxJS) in terms of client implementation?

Before anyone considers downvoting or closing my question, I want to clarify that I am not asking which option is better (as this would be an irrelevant question considering one focuses on the server and the other on the browser). In this straightforward ...

Error: When running the NPM CI command in a GitHub action, the package nice-napi is not accessible from

I've recently set up a Github action to build and run tests on every pull request. However, the action suddenly stopped working even though no changes were made to the code base. Here is the current code for the action: name: Test pull request on: ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

Experiencing a hitch when attempting to deploy an Angular 2 application on Heroku

Encountering the sh: 1: tsc: not found Error when attempting to deploy an Angular 2 app on Heroku. Using Node version: v7.2.0 and npm Version: v4.0.3. View the error on Heroku Any suggestions on how to resolve this issue? ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

NativeScriptException: Module "crypto" cannot be located

Attempting to implement the openpgp library for encryption in nativescript, I successfully installed and ran it. However, upon trying to use it, an error occurred: JS: Angular is running in the development mode. Call enableProdMode() to enable the product ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Combining Pixie Image Editor with Ionic 3.X

I am attempting to connect Pixie Image Editor with Ionix 3.X. After trying to install it via npm install "Path of the source folder provided in the package" The installation message reads "pixie": "file:pixie" in package.json, but I encounter an error wh ...

Refreshing the private route redirects the user to the login page

Currently, I am working on setting up a private route within my React app. I have integrated Redux and Redux-Toolkit (RTK) Query for handling state management and data fetching. The issue I am facing is that whenever I reload the private page, it redirects ...

My instance transforms with the arrival of a JSON file

I'm grappling with a query about data types in TypeScript and Angular 2. I defined a class in TypeScript export class product{ public id:number; public name:string; public status:boolean; constructor(){} } and I initialize an instanc ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

Tips for incorporating Response_type id_token+code into a login URL within an Angular application through the MSAdal library

We are currently utilizing the msadal library for Azure ad B2C login. I am now looking to include the response_type in the URL https://login.microsoftonline.com/common/oauth2/authorize when a user logs in. Here is the code being used for login: if (!this ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Acquire the Angular Type<> directly from the component instance in Angular 5

First and foremost, I want to clarify that my requirement is for the Angular Type instance of a component, not just the TypeScript definition. The current scenario is as follows: I am working within a service where I receive an input of the actual instanc ...

AfterViewInit is not being impacted by property binding in the view

I'm currently integrating Mapbox into my Angular project and I am facing a challenge in displaying information from my component.ts file in the corresponding component.html. My approach involves using mat-vertical-stepper, where each step represents ...