【问题标题】:Cloud Firestore updating a modified documentCloud Firestore 更新修改后的文档
【发布时间】:2018-05-08 12:58:27
【问题描述】:

我在我的 Angular (4) 应用程序中使用 angularFire2 和 Cloud Firestore 获得了一个项目列表,以获取 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 };
    });
  });

然后我用 *ngFor 和异步管道在我的组件中列出这个 Observable:

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

这很好用,当我添加一个新项目时,它会自动显示在列表中。尽管如此,当我更新一个项目的分数时,Observable 会更新,但我仍然看到该项目的旧版本(不是带有新分数的更新版本)。如果我点击刷新,我会看到更新的版本。

我这样更新一个项目的分数:

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

}

当我更新一个项目的分数时,我该怎么做才能在 Observable 中自动看到更新的项目?

【问题讨论】:

    标签: angular typescript angularfire2 google-cloud-firestore


    【解决方案1】:

    Angular 的 observable 不是这样工作的。您需要向观察者提供值以刷新可观察对象。您将需要覆盖您的变量以启动刷新。像这样:

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

    我希望我是对的:)

    【讨论】:

    • 您好 Witold,非常感谢您的回答。我按照您所说的进行了尝试,在更新后重新创建 Observable 项目并且它可以工作,但似乎有点矫枉过正。更新后我再做一次: this.itemCollection = afs.collection('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; 返回 { id, ...data }; }); }); observable 不应该自动更新值而无需重新创建它吗?
    • 不幸的是,我认为这不会像您期望的那样工作。您可以创建一个刷新函数并重新创建您的 items 函数,或者创建一个函数,手动将您的更改引入items 变量然后更新它(推荐)。
    猜你喜欢
    • 2018-09-21
    • 2021-06-11
    • 2019-10-23
    • 2021-01-24
    • 2018-11-28
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多