0

My Firebase Firestore database is like this:

Collection:orders
    DocumentID: (autogenerated)
         Document: orderName: string

Variables declared like this:

    orderCollection: AngularFirestoreCollection<Order>
    orders: Observable<Order[]>

I am getting all 'orders' like this:

orderCollection = this.afs.collection('orders');
orders = this.orderCollection.valueChanges();

I am then printing the orders like this:

<tr *ngFor="let o of orders | async">
    <td>{{o.orderName}}</td>
    <td><a (click)="editOrder(o.$key)">Edit</a></td>
</tr>

I everything is working perfect up to the edit part.

For edit: how to I send back the document ID of the order? I want to send the order document ID back so I can then edit it. With the realtime database you could do something with $key, but not with the firestore. Suggestions?

Hayden
  • 43
  • 3
  • 9

2 Answers2

1

In AngularFirestore it is simply document.id. But for this to work you must use snapshotChanges instead of valueChanges. So:

orders = this.orderCollection.snapshotChanges();

And then:

<tr *ngFor="let o of orders | async">
    <td>{{o.data().orderName}}</td>
    <td><a (click)="editOrder(o.id)">Edit</a></td>
</tr>

Inspired by: Firestore Getting documents id from collection and Get Collections with Document Ids Included.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I have the variables declared as follows:

    orderCollection: AngularFirestoreCollection
    orders: Observable

    this.orderCollection = this.afs.collection('orders');
    this.orders = this.orderCollection.snapshotChanges();

    but with the snapshotChanges(), I am getting the error on this.orders:
    type 'Observable[]>' is not assignable to type 'Observable'.
    Any ideas?
    – Hayden Jul 23 '18 at 01:39
0

Import this

import { map } from 'rxjs/operators';

and in your interface make sure contain id

export interface Order{
  id?:string
  foo1?: string
  foo2?: string
  foo3?: string
}

and your function look like this

this.orderCollection = this.afs.collection<Order>('orders');
 this.orders = this.orderCollection.snapshotChanges().pipe(
      map(kazi => {
      return kazi.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;

          return { id, ...data };
      });
      })
  );

get result

  this.orders.forEach(order =>{
      console.log(order)   
})

I hope that will help