How to Retrieve the DocumentID in Angular Firestore

My struggle lies in accessing the document ID in Firestore. While I am able to create a randomly generated document ID, I am having trouble retrieving it for use in a delete function. The custom document ID option is also causing errors and confusion for me. I am attempting to either find a way to access the document ID for each item listed in the loop within the HTML, or to generate unique doc IDs such as parsed image URLs.

import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { WebcamImage } from 'ngx-webcam';
import { HttpClient } from '@angular/common/http';
import { visionApi } from 'src/environments/environment';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthorizationService } from '../auth-service.service';
import { AngularFirestoreModule, AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { BusinessCardServiceService } from '../business-card-service.service';

interface BusinessCard {

  imageUrl: string;
  name: string;
  email: string;
  phone: string;
  fullText: string;
}
...
import { Injectable } from '@angular/core';
import { AngularFirestoreModule, AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { WebcamImage } from 'ngx-webcam';
...

@Injectable({
  providedIn: 'root'
})
export class BusinessCardServiceService {
 ...
<ul>
    <div *ngFor='let card of businessCards | async'>
        <div>{{card.name}} <button class="updateButton">Update Name</button></div>
        <div>{{card.email}} <button class="updateButton">Update Email</button></div>
        <div>{{card.phone}} <button class="updateButton">Update Phone Number</button></div>
        <img [src]='card.imageUrl' />
        <div><button class="DeleteButton">Delete Card</button></div>
    </div>
</ul>

Answer №1

snapshotChanges() is a useful function in Angular that provides document metadata with the document id included. If you're interested, you can see an example of how to implement this function. After obtaining the ID, data deletion can be carried out following Google Cloud Firestore's guidelines. For more insights on retrieving document IDs from collections, check out some responses here.

Answer №2

If you're using the valueChanges method to subscribe to this query within the WebCamComponent,

this.cardCollection = this.afs.collection<BusinessCard>('Users/' + this.uid + '/BusinessCards' + this.uid);
this.businessCards = this.cardCollection.valueChanges();

However, keep in mind that valueChanges does not provide all metadata, it only returns the value. It's recommended to use snapshotChanges (see here) to also retrieve the key.

You'll need to unpack the result to include the id in the BusinessCard object. The id will be accessible through doc.id, while the other fields you already have will be under doc.data.

Since snapshotChanges provides more metadata (including the type of change), you must handle it accordingly. Here's an example code snippet to guide you:

this.businessCards = this.cardCollection.snapshotChanges().pipe(
  map(actions => actions.map(a => {
    const data = a.payload.doc.data() as BusinessCard;
    data.id = a.payload.doc.id;  
    return data;
  }))
);

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

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

How can I postpone the initialization of ngOnInit in Angular 7?

While attempting to send and retrieve data for display, I encountered an issue where the component initializes before the new data is added to the server. This results in a missing element being displayed. Is there a way to delay the initialization proce ...

The vertical lines separating the buttons are not evenly centered

I need help to center a vertical line between my buttons in the middle of the header. Currently, the line goes up and my disconnect button is not aligned properly. Can you assist me in creating a responsive design? Thank you. https://i.sstatic.net/XIeiQ4E ...

A special function designed to accept and return a specific type as its parameter and return value

I am attempting to develop a function that encapsulates a function with either the type GetStaticProps or GetServerSideProps, and returns a function of the same type wrapping the input function. The goal is for the wrapper to have knowledge of what it is ...

Working with JSON in the Angular frontend

Looking for assistance to display my JSON data in an Angular frontend in a tree-like structure or an extension. Here is my backend JSON, it consists of a Buildings array grouped by campuses for relational MongoDB databases. [ { "_id": "campus4", "bui ...

Resolving compatibility issues between FullCalendar and Angular 8

Encountering an issue in the console while using Angular 8: The error message reads: Module '../../../../../../../../node_modules/@fullcalendar/angular/fullcalendar-angular' has no exported member 'CalendarOptions'. Past solutions inv ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

Issue with integrating Angular and bootstrap-star-rating V4.1.0

I tried incorporating the bootstrap-star rating v4.1.0 from here, but unfortunately, it's not functioning as expected in my project. In my index.html file, I have included the following libraries: <!DOCTYPE html> <html lang="en"> ...

How can I create a custom validator in Angular 2 that trims the input fields?

As a newcomer to Angular, I am looking to create a custom validator that can trim the input field of a model-driven approach form. However, I have encountered difficulties during implementation. When attempting to set the value using setValue() within th ...

Determining the size of a custom-typed array in Typescript

Can anyone explain how to find the length of a custom typed array? For example: type TMyArray = IProduct[] interface IProduct { cost: number, name: string, weight: number } So, how can we determine the length in this case: const testArr: TMyArray ...

What are the different types of class properties in TypeScript?

Currently, I am incorporating ES6 classes in typescript using the following code snippet: class Camera { constructor(ip) { this.ip = ip; } } Despite encountering an error message, it appears that the code still compiles successfully. The ...

Navigating the pathway to retrieving variables within an Angular Component function

export class MapsComponent implements OnInit { @ViewChild('googleMap') gmapElement: any; map: google.maps.Map; data = "initialised"; ngOnInit() { var directionsService = new google.maps.DirectionsService; ...

Start incrementing from the value of x

I'm trying to create an incremental column in Node.js with TypeORM, similar to this: @Column() @Generated('increment') public orderNumber: number; Is there a method to set TypeORM to begin counting from 9000 instead of the default starting ...

Develop your own personalized Angular schematics that produces a file that begins with an underscore

Having trouble with custom Angular schematics file naming. I'm trying to create a theme SCSS file that starts with an underscore followed by a double underscore as a delimiter. For instance, I want the file name to be _mouse-theme.scss, using the nam ...

Retrieve the dimensions of a child component when NgIf condition is met

I am facing a situation where I have a main component with a child component that is populated using NgFor. To control the visibility of the child, the parent sets a property called childIsVisible to false and binds it to the child using *ngIf="childIsVisi ...

The status property in Angular 4 is currently not defined or is referencing a null value

I am currently working with angular 4 and ionic 3, and encountering an error message that says unable to get property 'status' undefined or null reference from the JSON data I am displaying on my HTML page. Here is a snippet of my home.ts file: ...

Issues with Angular dependencies encountered during the pipeline process

An interesting series of events unfolded before me. The Angular website application seemed a bit outdated, possibly version 3, and was then upgraded to version 8.2.8. However, the upgrade couldn't be completed all the way due to a dependency on mdbbo ...

Navigating to a specific section in Angular 6 by scrolling to an

I am having trouble setting up an anchor on my Angular 6 page. When I include the following configuration: imports: [RouterModule.forRoot(routes,{'anchorScrolling': 'enabled',})], I encounter the following error: Unable to assign type ...

What settings do I need to adjust in order to set up VSCode to be compatible with TypeScript

I'm currently struggling to set up VSCode with TypeScript and facing some difficulties. My focus is on the following: https://code.visualstudio.com/docs/languages/typescript It seems like after installing the compiler, VSCode should function proper ...