Accessing collection values from referenced document IDs in Firestore---I have provided a unique version of the text

I have two fire store collections with the following reference images: https://i.sstatic.net/QVJkZ.pnghttps://i.sstatic.net/0QFRi.png. I am trying to retrieve the firstName and title from these collections. The signup_id is referenced from the document id of coll-signup. Below is the code snippet of what I have done so far:

Model feed.ts

export interface Feed {
    firstName? : string;
    signup_id? : string;
    title? : string;
}

news feed.component template

<ul *ngFor="let feed of feeds">
<!-- <li>{{feed.firstName}}</li> --> // Here I want to display my first name
      <li>{{feed.title}}</li>
      <li>{{feed.signup_id}}</li>
    </ul>

news-feed.component.ts

import { Component, OnInit } from '@angular/core';
import { Feed } from '../../models/feed';
import { FeedService } from '../../services/feed.service';
@Component({
  selector: 'app-news-feed',
  templateUrl: './news-feed.component.html',
  styleUrls: ['./news-feed.component.css']
})
export class NewsFeedComponent implements OnInit {
  feeds : Feed[];
  constructor(private feedService: FeedService) { }

  ngOnInit() {
    this.feedService.sellectAllNews().subscribe(feeds => {
      this.feeds = feeds;
    })
  }

}

feed.service.ts

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
    import { Observable } from 'rxjs/Observable';
    import { Feed } from '../models/feed';
    @Injectable()
    export class FeedService {
      feedCollection : AngularFirestoreCollection<Feed>;
      feedItem : Observable<Feed[]>;
    
      constructor(private afs : AngularFirestore) { 
        this.collectionInitialization();
      }
    
      collectionInitialization() {
// I think here I have to modify or add next collection to will get the output
        this.feedCollection = this.afs.collection('col-challange');
        this.feedItem = this.feedCollection.stateChanges().map(changes => {
          return changes.map(a => {
            const data = a.payload.doc.data() as Feed;
            return data;
          })
        })
    
      }
      sellectAllNews() {
        this.collectionInitialization();
        return this.feedItem;
      }
    }

Is it possible to achieve this in Firestore? I am new to Firestore. Any help would be appreciated. Thank you!

Answer №1

To merge two collections, you can use the code snippet below:

this.firstCollection = this.afs.collection('collection-one');
this.secondItem = this.firstCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        // Retrieve data excluding first name
        const newData = a.payload.doc.data() as Data;
        // Obtain signup_id to fetch document from coll-signup
        const signupId = newData.signup_id;
        // Fetch related document
        return afs.collection('coll-signup').doc(signupId).snapshotChanges().take(1).map(actions => {
          return actions.payload.data();
        }).map(signup => {
          // Format data according to feeds interface
          return { firstName: signup.firstName, ...newData };
        });
      })
    }).flatMap(items => Observable.combineLatest(items));

Answer №2

If you are facing challenges with merging documents in Firebase Cloud Firestore with Angular6, RxJS 6, and AngularFire v5.0, consider implementing the following code snippet:

Define models in feed.ts

export interface Feed {
  firstName?: string;
  signup_id?: string;
  title?: string;
}

export interface CollSignup {
  firstName: string;
  mob: string;
}

export interface ColChallange {
  signup_id: string;
  title: string;
}

Create a service in feed.service.ts

import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable, combineLatest } from 'rxjs';
import {flatMap, map} from 'rxjs/operators';
import {ColChallange, CollSignup, Feed} from '../../models/feed';

@Injectable()
export class FeedService {
  colChallangeCollection: AngularFirestoreCollection<ColChallange>;
  feedItem: Observable<Feed[]>;

  constructor(private afs: AngularFirestore) { }

  collectionInitialization() {
    this.colChallangeCollection = this.afs.collection('col-challange');
     this.feedItem = this.colChallangeCollection.snapshotChanges().pipe(map(changes  => {
      return changes.map( change => {
        const data = change.payload.doc.data();
        const signupId = data.signup_id;
        const title = data.title;
          return this.afs.doc('coll-signup/' + signupId).valueChanges().pipe(map( (collSignupData: CollSignup) => {
            return Object.assign(
              {firstName: collSignupData.firstName, signup_id: signupId, title: title}); }
          ));
      });
    }), flatMap(feeds => combineLatest(feeds)));
  }

  sellectAllNews() {
    this.collectionInitialization();
    return this.feedItem;
  }
}

To display all the data

this.feedItem.forEach(value => {
  console.log(value);
});

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

:id Path replaces existing routes

My route configuration looks like this: const routes: Routes = [ { path: '', component: UserComponent, children: [ { path: '', component: LoginComponent }, { path: 'signup', component: SignupComponent } ]}, ...

Error encountered: Firebase cloud function in Node.js V10 has experienced a parsing issue due to an unexpected token 'select

Each time I try to deploy my cloud function, I encounter a Parsing error: Unexpected token selectWinner. I attempted to resolve this by updating the parser options in .eslintrc.json to utilize ecmaVersion 2017, but unfortunately, that did not solve the is ...

What is the best way to implement persistStore in Redux-Toolkit?

Here is my setup: import AsyncStorage from '@react-native-async-storage/async-storage' import { persistStore, persistReducer } from 'redux-persist'; import { configureStore } from "@reduxjs/toolkit"; import { searchReducer } f ...

Styling with CSS in Angular 2+ can be quite challenging

Hey there, I'm new to Angular 4 and running into some troubles with styling my application. I tried adding a background image to the body, which worked fine, and then added a component to display content, also looking good. Now, when I added a second ...

Struggling to determine the necessary modules to import in order to successfully integrate Firestore with Angular services

Recently, I developed a simple service with the following structure: @Injectable({ providedIn: "root" }) export class ItemService { private db!: CollectionReference<DocumentData>; constructor(private firestore: Firestore) { this. ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

Displaying Firebase data using Angularfire2 5.0 on an Ionic template

Hey everyone, I've been encountering a problem while trying to use angularfire2 v 5.0. I was comfortable using v 4.0 before, but now that I'm transitioning to v 5.0, I'm facing some issues. Does anyone know how I can display real-time data ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Having trouble injecting HttpClient in a hybrid AngularJS/Angular app that has been upgraded with ngUpgrade? You may come across the error message "NullInjectorError: No provider for http_HttpClient!"

My AngularJS/Angular hybrid app, upgraded with ngUpgrade, has been functioning well. The new Angular components (downgraded) work seamlessly in the AngularJS app. However, I'm encountering an issue where the HttpClient module fails to instantiate. I ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

What is the best way to showcase a diverse list with varying templates using Angular?

Looking to showcase a variety of items sourced from a service, each potentially belonging to different types. I am in search of a way to dynamically display distinct templates for each item based on its value or type. Is there a functionality that allows ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Error: The function list.forEach does not exist within service.buildList [as project]

Today, I've been grappling with a challenging issue. As someone new to Typescript and Angular, I'm attempting to make a call to my backend API. However, when trying to populate an array for display, I keep encountering an error that says rawRegis ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

Show the content exclusively on the main landing page; once you move to a different section, the display should disappear

Let's say I have multiple components - Home, One, Two, and Three. Using navigation and routing, each page can be accessed. I only want to show a message "Hello" on the Home page and hide it on all other pages. Check out this Stackblitz example The b ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...

Leveraging Observables with ngrx for efficient async pipe implementation

Trying to create a shadow copy of pending changes using observables and ngrx has presented me with a puzzling issue: export class SearchBoxContainerComponent { filterSettings$: Observable<FilterSettings>; filterChanges: {[key:string]: any}; ...

Having trouble retrieving the parent object in Angular OnInit method?

I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck is true. ...