5
votes

I want to read a specific document in Firebase Firestore using AngularFire.

import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore , AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { async } from 'q';

@Component({
  selector: 'app-read-more-page',
  templateUrl: './read-more-page.component.html',
  styleUrls: ['./read-more-page.component.scss']
})
export class ReadMorePageComponent implements OnInit {
  postCatagory: string;
  databaseName: any; 
  uuid: string;

  documentObject:any; //real docum

  //observables 
  items: Observable<any[]>;
  doc  : AngularFirestoreDocument<any>
  post : Observable<any>;

  constructor(private route: ActivatedRoute , private afs: AngularFirestore ) {
    this.databaseName = this.route.snapshot.paramMap.get('category'); 
    this.items = afs.collection(this.databaseName).valueChanges();
  }   

  ngOnInit() {
    if(this.route.snapshot.paramMap.get('uuid') != null){ 
      //when id is not null   
      this.databaseName = this.route.snapshot.paramMap.get('category');
      this.uuid = this.route.snapshot.paramMap.get('uuid');
      console.log("UUID " , this.uuid);
      console.log("category "  ,this.databaseName);
      //read data from collection 
      //read post 
      this.doc = this.afs.doc(`${this.databaseName}/${this.uuid}`); 
    }
  }
}

${this.databaseName}/${this.uuid} is the document I wanted to read. But as the example in firestore docs, we could easily read all the documents from the collection. But I need to retrieve only the exact document.

I'm still a beginner so I would be much thankful if you could provide some beginner-friendly content

1

1 Answers

6
votes
const docRef = afs.collection('collectionName').doc('documentId');

it will give you document reference, then you can subscribe to snapshotChanges() or call data() or other methods