简体   繁体   中英

How to get particular document data with id ? | AngularFire 5.1.1 | Cloud Firestore | Documents

I am using Data access service to get the data from firebase firestore.

How to use snapshotChanges()method for getting particular document data with id

getProduct(id: number): Observable<Product> {
    this.productsDocuments = this.angularfirestore.doc<Product>('products/' + id);
    this.product = this.productsDocuments.snapshotChanges().pipe(
      map(changes => changes.map(a => {
        const data = a.payload.doc.data() as Product;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
    return this.product

I want this.product returns the document value and document id

Thank You!!

a document is simply an object {[field]: value} and collection is a container for documents [document]

you are trying to get a single document aka object and the problem here that you cannot map it directly, i think that you wanna get the entire collection, if! you can know map over all documents

getProduct(id: number): Observable<Product> { const productsDocuments = this.db.doc<Product>('products/' + id); return productsDocuments.snapshotChanges() .pipe( map(changes => { const data = changes.payload.data(); const id = changes.payload.id; return { id, ...data }; })) }

for collection

getProduct(id: string): Observable<Product[]> { const productsDocuments = this.db.collection<Product[]>('products'); return productsDocuments.snapshotChanges() .pipe( map(changes => changes.map(({ payload: { doc } }) => { const data = doc.data(); const id = doc.id return { id, ...data }; })), map((products) => products.find(doc => doc.id === id))) }

sorry for bad english

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM