What are the steps to combine two collections using rxjs?

I need to combine two collections (tokens and trends) based on their IDs, where each item in the result should include data from both collections. This means that the ID of an item in the trends collection matches the ID of the corresponding item in the tokens collection.

To achieve this merging of documents, I have devised the following function:

export interface TokenData {
    created_utc: number;
    image: string;
    name: string;
}

export interface usersCount {
    subscribers: number;
    visitors: number;
    timestamp: number;
}

export interface TrendData {
    tokenInfo: TokenData;
    users_count: usersCount[];
}

getTrends(): Observable<TrendData[]> {
      const tokens = this.db.collection<TrendData>('tokens').snapshotChanges()
      .pipe(map(docArray => {
        return docArray.map(doc => {
          const data: any = doc.payload.doc.data();
          return {
            id: doc.payload.doc.id,
            ...data
          };
        });
      }));
      const trends = this.db.collection<TrendData>('trends').snapshotChanges()
      .pipe(map(docArray => {
        return docArray.map(doc => {
          const data: any = doc.payload.doc.data();
          return {
            id: doc.payload.doc.id,
            ...data
          };
        });
      }));
      const fj = forkJoin({
        tokens: tokens,
        trends: trends
      });
      return fj.pipe(map(items => {
        return items.trends.map(trendItem => {
          return {
            tokenInfo: items.tokens.find(({id}) => id === trendItem.id),
            users_count: trendItem
          }
        })
      }))
    }

My main goal is to merge data from two Firestore collections, but currently, the function is not returning anything. I am unsure if forkJoin is the correct operator for this task or if there might be some other issue causing the subscribed function to not fetch the data.

Answer №1

Switching to combineLatest from forkJoin resolved the issue:

fetchTrends(): Observable<TrendData[]> {
      const tokensData = this.db.collection<TrendData>('tokens').snapshotChanges()
      .pipe(map(arrayOfDocs => {
        return arrayOfDocs.map(doc => {
          const data: any = doc.payload.doc.data();
          return {
            id: doc.payload.doc.id,
            ...data
          };
        });
      }));
      
      const trendsData = this.db.collection<TrendData>('trends').snapshotChanges()
      .pipe(map(arrayOfDocs => {
        return arrayOfDocs.map(doc => {
          const data: any = doc.payload.doc.data();
          return {
            id: doc.payload.doc.id,
            ...data
          };
        });
      }));
      
      const combinedData = combineLatest([tokensData, trendsData]).pipe(
        map(([tokens, trends]) => {
          return trends.map(trendItem => {
            return {
              tokenInfo: tokens.find(({id}) => id === trendItem.id),
              users_count: trendItem
            }
          })
        })
        )
      return combinedData;
    }

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

What advantages do interfaces as data types offer in Angular compared to using classes?

After watching a tutorial from my teacher, he showed us this code snippet: https://i.sstatic.net/MA3Z9.png He mentioned that the products array, defined as type any [], is not taking advantage of TypeScript's strongly typing. He suggested using an I ...

Find the maximum value in an array of enumerated items

Let's consider an enum enum enumerationTmp { a, // 0 b, // 1 c // 2 } and an array containing elements from this enum const letters = [enumerationTmp.a, enumerationTmp.b] How would one determine the maximum value in the array 'letters& ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

Using TypeScript: creating functions without defining an interface

Can function props be used without an interface? I have a function with the following properties: from - HTML Element to - HTML Element coords - Array [2, 2] export const adjustElements = ({ from, to, coords }) => { let to_rect = to.getBoundingC ...

Module Augmentation for extending Material UI theme is not functioning as expected

I'm having trouble expanding upon the Theme with Material UI because an error keeps popping up, indicating that I am not extending it correctly. The error message states: Property 'layout' is missing in type 'Palette' but required ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...

Utilize TypeScript File array within the image tag in HTML with Angular 2

I am in the process of developing a web application that allows users to upload CSV data and images, which are then displayed on the application. However, I have encountered an issue where I am unable to display the imported images. The images are imported ...

Is there a way to perform type narrowing within an Angular template?

I'm facing an issue with a component that requires a business object as an Input. Within the template of this component, I need to conditionally display some content based on the presence of a property that only exists in certain subclasses of the bus ...

Obtaining a list of dates for a particular week using React DayPicker

I'm seeking the ability to click on a specific week number within the react DayPicker and receive an array of all dates within that week. The DayPicker package I am using can be found here: I've copied the example code from react DayPicker to e ...

transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties. Here is the initial array: const json = [{ "ID": 10, "Sum": 860, "class": "K", }, { "ID": 10, "Sum": 760, "class": "one", }, { "ID": ...

How can debugging in Chrome be achieved using Typescript?

How is it possible to debug TypeScript in Google Chrome when the browser only understands JavaScript? I find myself debugging my TypeScript files within my Angular project, which was created using Angular CLI, through the Chrome developer tools. However, ...

Using RxJS v5 for Sending a POST Request with Parameters

Snippet of my RxJS code: .mergeMap(action => { const user = store.getState().user; return ajax.post(`${config.API_BASE_URL}/api/v1/rsvps`, { rsvp: { meetup_id: action.payload, user_id: user.id, } }) .map(action => calenda ...

What causes the "Error: method not allowed" message to appear when attempting to send a "DELETE" request from a Next Js component? (The POST method is

This is my first time on this platform, and I'm currently following a tutorial from Javascript Mastery to create a clone of a thread application. After watching the entire video and building the basic functionality based on it, I decided to enhance th ...

Utilizing PrimeNg with Angular 2 to dynamically update charts using @ViewChild

I'm currently utilizing Angular2 with PrimeNG for my application. My dashboard includes charts and after attempting to upgrade to PrimeNG rc7 (from rc5) where they addressed an issue with updating charts, I'm facing challenges updating my chart d ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Generics causing mismatch in data types

I decided to create a Discord bot using DiscordJS and TypeScript. To simplify the process of adding components to Discord messages, I developed an abstract class called componentprototype. Here is how it looks (Please note that Generators are subclasses li ...

Enhancing Forms with Redux and Styled Components

I'm currently working on developing a reusable component that involves using a redux-form <Field /> and styling it with styled-components within the component. The issue I'm facing is that none of the styles are being applied. Here is my ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...