在我的 Firebase Firestore 資料庫中添加新資料時,我遇到了這種情況。
forEach將迭代檔案(Firebase 檔案)的值,同時ngFor在前端呈現資料。這種資料重復只會發生在頁面沒有重新加載并且添加新資料時,如果用戶重新加載頁面,復制就會停止。
我在這里瘋狂猜測,如果頁面可以自動重新加載可以解決,但不幸的是資料的添加發生在其他頁面中。
這是要了解更多的影像:(如果您注意到,一些資料在前端重復,但如果用戶重新加載頁面,它將恢復正常)。

主頁.html
<div *ngIf="!auth.canDelete(user)">
<ion-grid>
<ion-row>
<ion-col size-lg="3" size-md="4" size-sm="6" size="12" *ngFor="let o of orgInfo">
<ion-card>
<div class="container">
<ion-img class="img" [src]="o.imageUrl"></ion-img>
</div>
<ion-card-header>
<ion-card-title class="truncateWord">{{ o.orgName }}</ion-card-title>
<ion-card-subtitle>{{ o.userList?.length > 0 ? o.userList?.length : '0' }} member/s</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
<p class="truncateWord">{{ o.description }}</p>
</ion-card-content>
<ion-button fill="solid" class="ion-margin" expand="block" color="primary" [routerLink]="['/home', o.orgId]">
<ion-icon name="open" slot="start"></ion-icon>
<ion-label>View</ion-label>
</ion-button>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</div>
主頁.ts
this.organizationList.forEach(uid => {
const docRef = firebase.firestore().collection("organization").doc(uid);
docRef.get().then((doc) => {
if (doc.exists) {
this.orgInfo.push({
orgId: doc.data().orgId,
orgName: doc.data().orgName,
description: doc.data().description,
imageUrl: doc.data().imageUrl,
userList: doc.data().userList
});
this.orgInfo.sort((a, b) => (a.userName > b.userName) ? 1 : -1);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
});
uj5u.com熱心網友回復:
如果您有 doc.data() 回傳的唯一值,您可以檢查 orgInfo 陣列是否已經包含具有該值的物件,并且僅在沒有此類物件時才推送到 orgInfo:
if (doc.exists) {
// assumption: doc.data().orgId is a unique value:
if (!this.orgInfo.some(e => e.orgId === doc.data().orgId)) {
// this.orgInfo doesn't contain the item, so we can add it:
this.orgInfo.push({...});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408147.html
標籤:
