Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangular-reactive-forms

Get a single data from firebase in Angular


I want to get data from firebase by id and populate an update form. So first to get the id , I have the following but it returns all the id s as an array. How do I just get a single one after clicking on a list of data? After clicking the specific data, it takes me to the update form(reactive).As mentioned I want the update form to be populated by the id. The id is also passed to the link i.e client/id . In service

getClient(id:any){
    return this.db 
    .collection('clients')
    .snapshotChanges()
    .pipe(map(docData => {
      return docData.map(doc => {
        return {          
          id: doc.payload.doc.id                  
        };
      });
    }))
    .subscribe(result => {
          console.log(result);
       });
    
  }      
                                 }

This returns all the id in the firbase but I want only the one clicked and populate the form accordingly.


Solution

  • Since you already have an ID, and you're passing it as argument to your getClient method, you can read the document directly. Your code should look like this:

    getClient(id:any) {
        return this.db 
        .collection('clients')
        .doc(id)
        .get()
        .subscribe(doc => {
           console.log(doc.data());
        });
    }  
    

    That's it. In your code, instead, you were listening for any changes that occur to your entire collection, not just the single document, and you were being notified everytime.