A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it.

Within app.module.ts, kicking things off with:

    import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
    import { getFirestore, provideFirestore } from '@angular/fire/firestore'
    
imports: [
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
],

Created a FirestoreService for data retrieval and updates.

Updates on array in documents are smooth sailing, but querying Firestore has me puzzled - always ending up with undefined results.

import { AngularFireAuth } from '@angular/fire/compat/auth';
import {
  Firestore,
  getFirestore,
  provideFirestore,
  collectionData,
  collection,
  doc,
  getDoc,
  docData,
  query,
  setDoc,
  updateDoc,
  addDoc,
  firestoreInstance$,
  DocumentData,
  arrayRemove,
} from '@angular/fire/firestore';

// More code followed by a rejection method...

async rejectFriendRequest(rejectedUser: string, currentUser: string){
    const recipientRef = doc(this.firestore, "users", JSON.stringify(currentUser));

    await updateDoc(recipientRef, {
      invitationsFrom: arrayRemove(rejectedUser),
      rejectedInvitation: arrayUnion(rejectedUser)
    });
  }

The rejection method is doing its job updating arrays in specific documents. However, reading documents from Firestore has hit a roadblock, unsure about which library to use next. The initial idea was to use email addresses as document IDs, but faced issues when needing to update an ID containing a ".".

One of my attempts involved this snippet:

async getUser(id: string) {

    var usersRef = this.aF.collection("users").doc(id);

    var colRef = collection(this.firestore, "users")
    var docreference = await doc(colRef, id);

    docData(docreference).subscribe( (result) => {
      console.log(result);
    })

  }

Answer №1

In order to monitor changes in the document, it is essential to set the document reference and use the valueChanges() method on that reference within your constructor. This will allow you to create an update method that can modify the item reference as it undergoes changes.

This approach is beneficial as it enables all methods to access it via this. You can refer to this Official example docs for more information.

import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';

export interface Item { name: string; }

@Component({
  selector: 'app-root',
  template: `
    <div>
      {{ (item | async)?.name }}
    </div>
  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}

To view information with minimal adjustments in your specific scenario, you should consider something like:

const itemDoc = this.firestore.doc(`users/${documentId}`);
const item = itemDoc.valueChanges();
console.log('item', item);

The presence of the second Firestore defined in your constructor seems out of place, so I recommend reviewing more examples.

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

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Obtaining a distinct identifier in Firebase

Hello, I'm currently working on a project using Firebase and I need to fetch all objects from the database. I've written the following code snippet to retrieve them: var ref = new Firebase("https://<fire-base-database>.firebaseio.com/games ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Angular class requires multiple class members and validators for MatSelection List to be bound with Formbuilder

Could you please guide me on how to connect the Google Angular Materials mat-selection-list with the FormBuilder? We have the following class and are attempting to utilize Reactive Form Builder for this purpose. While we are aware of how to link data class ...

Strategies for increasing the number of images in Angular

At the start, 15 images are displayed from the API. However, the "Get dogs" button should load an additional 15 images each time it's clicked, but currently, it doesn't work. How can we fix this issue? http.service.ts - a service that interacts ...

The term 'required' is not recognized as an identifier. There is no member by the name of '__type' in the definition

When working on my HTML template in the visual code editor, I encountered the need to declare a variable with type any? https://i.stack.imgur.com/Jq5az.png product-form.component.html <div class="row"> <div class="col-md-6"> <for ...

Error: Unable to access 'subscribe' property of empty object in Angular Unit Test

After making updates to an Angular component, I encountered issues with broken unit tests. All test specs are failing, leading me to believe that the problem lies in the initialization within the beforeEach calls. Despite extensive research, I have been un ...

The error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

Redirecting users to a different URL on my website using Firebase

My website was originally hosted on firebase at this URL: , but that version is now outdated. I recently updated the application and decided to switch to Vercel, hosting a new instance of my website at this URL: Now, I want to ensure that users don' ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Utilizing an array of data to create a complex structure with nested

In my Next.JS React project using TSX files, I have set up a data file like this: const fieldMapping = { category:[ { title: "Category 1", Subtitle: ["Category 1", "Category 2"], SubSubTitle: ["Category ...

"Discover the step-by-step process of building a vue.js3 application with typescript, vue-router, and vuex without relying on

I have been assigned the task of developing a Vue3 application with TypeScript support using Vuex for state management and vue-router for basic routing. However, I am not allowed to use vue-cli for this project. Here is my current code: <head> & ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

Is it possible to dynamically check values in TypeScript?

[Summary] I am looking to dynamically expand my type in TypeScript based on an initial set of values. I want to avoid managing separate arrays/types and instead extend all strings in my type with '_max'. type ExtendedValueTypes = 'money&apos ...

Module `coc-tsserver` not found (error ts2307)

https://i.sstatic.net/k1MVW.png Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the s ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Error: Uncaught TypeError - The function indexOf is not defined for e.target.className at the mouseup event in HTMLDocument (translator.js:433) within the angular

Upon clicking on an SVG to edit my data in a modal bootstrap, I encountered the following error: Uncaught TypeError: e.target.className.indexOf is not a function at HTMLDocument.mouseup (translator.js:433) This is my SVG code: <svg data-dismiss ...

Exploring the world of third-party APIs

I am currently working on fetching data from an external API and displaying it. In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead. Here is a brief visual ov ...

Angular Routing can be a powerful tool for managing multiple article posts in an efficient and organized way

I am in the process of building a website with Angular that features numerous articles. Whenever a user clicks on an article, I want it to navigate to a new URL using routing. To achieve this, I have created a new Article component and here is how my app- ...