2
votes

I got a list of items in my Angular (4) app using angularFire2 and Cloud Firestore to get an Observable:

private itemCollection: AngularFirestoreCollection<Item>;
items: Observable<ItemId[]>;
constructor(private readonly afs: AngularFirestore) {
  this.itemCollection = afs.collection<Item>('items');
  this.items = this.itemCollection.snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Item;
    const id = a.payload.doc.id;
    return { id, ...data };
    });
  });

I then list this Observable in my component with a *ngFor and an async Pipe:

<span *ngFor="let item of items | async">

This works great, and when I add a new item it automatically shows in the list. Nevertheless when I update the score of an item, the Observable updates, but I still see the older version of the item (not the updated one with the new score). If I hit refresh I see then the updated version.

I update the score of an item this way:

updateItem(id: string, score: number): void {
  this.collectionRef.doc(id).update({ score });

}

What can I do to see automatically the updated item in the Observable when I update the score of an item?

1

1 Answers

0
votes

Angular's observable didn't work like that. You need to provide value to an observer to refresh observable. you will need to overwrite your variable to initiate refresh. Like this:

updateItem(id: string, score: number): void {
  this.collectionRef.doc(id).update({ score });
  this.items = [already updated items document]
}

I hope I'm right :)