I'm looking to retrieve a specific file from my Angular Firestore database

I encountered a challenge in my latest project. I implemented Nested Children Routing to display data, and I want the specific item's data to be visible when clicking on the button. The routing is set up correctly, but I'm struggling to find the right function for the items.

Here is the service code:

PostsService.service.ts

getPostById(id: string){
    let docId = this.afs.collection('posts').doc(id).get()
      .subscribe( doc => {
        if(doc.exists){
          console.log('Document Id => ', doc.id)
          console.log('Document data => ', doc.data())
        }else {
          console.log('Document not found')
        }
      });
    return docId;   
}

And here is the TypeScript function for handling a single item:

.component.ts

posts: Posts[] = [];
post!:any;

constructor(
  private PostsService: PostsService, 
  private route: ActivatedRoute
) {}

ngOnInit(): void {
    let id = this.route.snapshot.params['id']
    this.PostsService.getPostById(id);
}

Answer №1

Instead of fetching the entire collection using getPostById(), you should directly retrieve the single document you need to avoid unnecessary reads and improve efficiency.

Remember, if you use getPostById(), make sure to utilize the returned data effectively instead of just making the request without any further action.

Why not simply fetch the specific document you require? This way, you can either continuously monitor it as an Observable or use its value immediately.

  getPostById(id: string) {
    const itemDoc = this.afs.doc<any>('posts/' + id);
    return itemDoc.valueChanges();
  }

Lastly, don't forget to unsubscribe from the Observable in your component to prevent memory leaks.

ngOnInit() {
  let id = this.route.snapshot.params['id'];
  this.PostsService.getPostById(id).subscribe(post => {
  console.log(post);
       })
   }

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

Using the jQuery library for asynchronous AJAX requests can lead to variables being replaced when loading data

I am facing an issue with my code that loads details about user payments one month in advance. The current function works fine when loading data for each month individually, but it fails when multiple ajax requests are made simultaneously. It seems like du ...

Adding a class to the body element in an HTML file using AngularJS

Greetings! Currently I am in the process of developing a web application using AngularJS SPA, which supports both English and Arabic languages. I am facing an issue with adding RTL and LTR properties by applying classes to the body HTML element in my app.j ...

Determine whether the current time falls within the specified time slots and check if the day is included in the provided array of days

Listing my Weekly Schedule: weekly_schedule: any[] = [ { id: 0, value: 'Monday' }, { id: 1, value: 'Tuesday' }, { id: 2, value: 'Wednesday' }, { id: 3, value: ...

Exploring the Viability of Utilizing TypeScript and ES6 Modules for a Compact Library Package

Currently, our team is in the process of developing a custom JavaScript library for integration with one of our flagship products. The development workflow involves: Utilizing TypeScript and internal modules to create namespaced classes (internal and pub ...

The functionality of the React Router DOM seems to be malfunctioning

I am facing an issue with running a program on my computer while it runs successfully on other PCs. When I try to run this program, I encounter the following error message. Any help in fixing this would be greatly appreciated... index.js import React, {C ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

Dynamically update multilayer markers on X-map using angular-maps

Utilizing Bing Maps (x-map) for displaying data in multiple layers on the map. The markers' data will be updated through a REST API call to the backend. I am facing an issue where the markers do not update on the map despite changing the data source. ...

Running into issues compiling Ionic 4 with Angular 7 inside a Docker container

Facing Issues Compiling Ionic 4 with Angular 7 in Docker I am trying to compile a project using Ionic 4 and Angular 7 within Docker. Here are the steps I have taken: I manually created an image with Java JDK version 8, following this article How To Ins ...

Tips for changing a specific item within an ng-repeat loop in AngularJS

Here is my HTML code: <tr ng-repeat="customer in customers"> <td> {{customer.customer_name}} </td> <td> {{customer.mobile}} </td> </tr> Upon executing this code, I receive 3 <tr>...</tr> blocks as s ...

Capturing a res.send(404) error in ExpressJS during production: Tips and tricks

Can middleware handle errors like 404 and 500 when they are returned this way? exports.index = function(req, res) { res.send(404); } In production, I would want to display a custom missing page for these errors. However, my error handler middleware doe ...

What is the best way to extract a JSON value and use it across multiple functions?

Currently, everything seems to be working fine. However, I'm unsure about the correct way to call the json data. I attempted using a direct link but it didn't work. Do I need to modify the "data" parameters? I'm confused because I saw that ...

Troubleshooting problem with Angular $scope and ng-if/ng-show: View status remains unchanged

Utilizing Firebase for authentication in my web app, I have implemented buttons on various pages that should only be visible when the admin is logged in. Despite using ng-if to display the button if 'loggedin' equals true, the buttons refuse to a ...

Is it possible to debug JavaScript functions using Visual Studio?

I'm intrigued about debugging javascript functions in Visual Studio. If it's feasible, kindly share with me the process. I am currently involved in an asp.net web application project. ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...

struggling to implement dynamic reactive forms with Angular

Currently, I am experimenting with building a dynamic reactive form using Angular. While I have successfully implemented the looping functionality, I am facing some challenges in displaying it the way I want. <form [formGroup]="registerForm" (ngSubmit) ...

Navigating with Three.JS FPS controls by moving left and right

Currently, I am working on a demo to check player controls for a FPS game. The camera rotation is controlled by the mouse, and the player can move using W-A-S-D keys. However, I am facing an issue with implementing movement left and right relative to the d ...

Achieve this unique effect with titanium scroll view elements

I recently came across a fascinating feature in some applications. The feature involves an image with the letter A positioned in a specific area. As I scroll up, the label containing the letter A moves upward until it reaches the top of the screen. At tha ...

Spot the columns generated by CSS and incorporate a new column using JavaScript

Exploring a column newspaper-like layout has led me to wonder if there is a way to use CSS or JavaScript to identify columns (or column breaks) and dynamically insert content between them with JavaScript. The concept involves having a layout with 100% hei ...

Using Array.splice() reveals a plethora of information

I'm facing an issue with the splice function. Here is my code snippet: const findMissingLetter=(array)=>{ let result, alphabet = "abcdefghijklmnopqrstuvwxyz"; if(array[0]===array[0].toUpperCase()) alphabet = alphabet.toUpperCase(); let start ...

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...