如何在使用Firebase删除列表项后更新列表?

huangapple go评论71阅读模式
英文:

How do i update the list after i delete an item from that list with Firebase?

问题

HTML:

<tr *ngFor="let value of imagesList">
    <td scope="row">{{value.id}}</td>
    <td>{{value.imageName}}</td>
    <td>{{value.warDate | date}}</td>
    <td><img src="{{value.screen}}" width="40px" height="40px" class="rounded-circle"></td>
    <td> {{ "dashboard.Download" | translate}}</td>
    <td><button type="button" class="btn btn-link" (click)="deleteWar(value)">{{ "dashboard.Delete" | translate}}</button></td>
</tr>

GET:

getAllUploadedImages() {

const auth = getAuth();
const user = auth.currentUser;

const q = query(collection(this.db, "warstats"), where("userId", "==", user?.uid));
const unsubscribe = onSnapshot(q, (querySnapshot) => {

  querySnapshot.forEach((doc) => {
    const data = doc.data() as WarImage;
    data.id = doc.id;
    this.imagesList.push(data as WarImage);
  });
 });
}

DELETE:

async deleteWar(image: WarImage) {
    await deleteDoc(doc(this.db, '/warstats/' + image.id));
}

问题如下:

如果列表中有3个项目,我删除了1个...列表会自动更新...但不是更新为2个项目,而是更新为5个项目...(我删除后的3个+删除前剩下的两个)..如果我刷新页面,它会正常显示只剩下的2个项目。

提前致谢。

英文:

i do an ngFor on a list and i show a table with multiple recordings. I have in my ts two methods, one for getAll and one for delete which are listed bellow:

HTML:

&lt;tr *ngFor=&quot;let value of imagesList&quot;&gt;
    &lt;td scope=&quot;row&quot;&gt;{{value.id}}&lt;/td&gt;
    &lt;td&gt;{{value.imageName}}&lt;/td&gt;
    &lt;td&gt;{{value.warDate | date}}&lt;/td&gt;
    &lt;td&gt;&lt;img src=&quot;{{value.screen}}&quot; width=&quot;40px&quot; height=&quot;40px&quot; class=&quot;rounded-circle&quot;&gt;&lt;/td&gt;
    &lt;td&gt; {{&quot;dashboard.Download&quot; | translate}}&lt;/a&gt; &lt;/td&gt;
    &lt;td&gt;&lt;button type=&quot;button&quot; class=&quot;btn btn-link&quot; (click)=&quot;deleteWar(value)&quot;&gt;{{&quot;dashboard.Delete&quot; | translate}}&lt;/button&gt;&lt;/td&gt;
&lt;/tr&gt;

GET:

getAllUploadedImages() {

const auth = getAuth();
const user = auth.currentUser;

const q = query(collection(this.db, &quot;warstats&quot;), where(&quot;userId&quot;, &quot;==&quot;, user?.uid));
const unsubscribe = onSnapshot(q, (querySnapshot) =&gt; {

  querySnapshot.forEach((doc) =&gt; {
    const data = doc.data() as WarImage;
    data.id = doc.id;
    this.imagesList.push(data as WarImage);
  });
 });
}

DELETE:

  async deleteWar(image: WarImage) {
    await deleteDoc(doc(this.db, &#39;/warstats/&#39; + image.id));
  }

The problem that i encounter is like this:

If have 3 items in the list and i delete 1 .. the list auto updates .. but instead of updating with 2 items it updates with 5 items .. ( the 3 that i had + the two taht remains after delete ) .. if i refresh the page, works good showing only the 2 remaining items.

Thank you in advance.

答案1

得分: 4

你应该在添加新数据之前清空imagesList数组。你可以修改你的代码:

import { Component, OnDestroy } from '@angular/core';
import { getAuth, query, collection, where, onSnapshot, deleteDoc, doc, QuerySnapshot } from 'firebase/firestore';
import { Subscription } from 'rxjs';

export class YourComponent implements OnDestroy {
  imagesList: WarImage[] = [];
  private snapshotSubscription: Subscription | undefined;

  getAllUploadedImages() {
    const auth = getAuth();
    const user = auth.currentUser;

    if (!user) {
      return;
    }

    const q = query(collection(this.db, "warstats"), where("userId", "==", user.uid));
    this.snapshotSubscription = onSnapshot(q, (querySnapshot: QuerySnapshot<WarImage>) => {
      this.imagesList = [];
      querySnapshot.forEach((doc) => {
        const data = doc.data();
        const id = doc.id;
        this.imagesList.push({ ...data, id });
      });
    });
  }

  async deleteWar(image: WarImage) {
    await deleteDoc(doc(this.db, '/warstats/' + image.id));
  }

  ngOnDestroy() {
    if (this.snapshotSubscription) {
      this.snapshotSubscription.unsubscribe();
    }
  }
}

此外,在组件销毁时记得取消订阅快照监听器。经过这些更改,当删除项目时,你的列表应该正确更新,只显示剩下的项目,无需刷新页面。

英文:

you should clear the imagesList array before adding the new data. You can modify your code

import { Component, OnDestroy } from &#39;@angular/core&#39;;
import { getAuth, query, collection, where, onSnapshot, deleteDoc, doc, QuerySnapshot } from &#39;firebase/firestore&#39;;
import { Subscription } from &#39;rxjs&#39;;

export class YourComponent implements OnDestroy {
  imagesList: WarImage[] = [];
  private snapshotSubscription: Subscription | undefined;

  getAllUploadedImages() {
    const auth = getAuth();
    const user = auth.currentUser;

    if (!user) {
      return;
    }

    const q = query(collection(this.db, &quot;warstats&quot;), where(&quot;userId&quot;, &quot;==&quot;, user.uid));
    this.snapshotSubscription = onSnapshot(q, (querySnapshot: QuerySnapshot&lt;WarImage&gt;) =&gt; {
      this.imagesList = [];
      querySnapshot.forEach((doc) =&gt; {
        const data = doc.data();
        const id = doc.id;
        this.imagesList.push({ ...data, id });
      });
    });
  }

  async deleteWar(image: WarImage) {
    await deleteDoc(doc(this.db, &#39;/warstats/&#39; + image.id));
  }

  ngOnDestroy() {
    if (this.snapshotSubscription) {
      this.snapshotSubscription.unsubscribe();
    }
  }
}

Also, remember to unsubscribe from the snapshot listener when the component is destroyed

With these changes, your list should update correctly when an item is deleted, showing only the remaining items without the need to refresh the page.

答案2

得分: 0

可能的问题是每次获取数据时都会将列表推送,这会将新数据添加到数组中已有的数据中。尝试在每次获取数据之前清空数组的内容,然后再保存新数据。希望我已经帮到你了!

const unsubscribe = onSnapshot(q, (querySnapshot) => {
    this.imagesList = [];
    querySnapshot.forEach((doc) => {
        const data = doc.data() as WarImage;
        data.id = doc.id;
        this.imagesList.push(data as WarImage);
    });
});
英文:

It is possible that the problem is that you push the list every time you do a get, which adds the new data to what was already in the array. Try removing the contents of the array before saving the new data each time you do a get. I hope I've helped!

const unsubscribe = onSnapshot(q, (querySnapshot) =&gt; {
          this.imagesList = [];
          querySnapshot.forEach((doc) =&gt; {
            const data = doc.data() as WarImage;
            data.id = doc.id;
            this.imagesList.push(data as WarImage);
          });
         });
        }

huangapple
  • 本文由 发表于 2023年7月24日 18:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定