我有一个应用程序,可以从用户集合中检索数据,其中clubId是外键(因为需要更好的术语)。
应用程序获取每个clubId的所有用户的计数,并在html表格中显示信息,显示俱乐部名称、与该俱乐部关联的用户数量以及显示每个俱乐部欠款金额的计算字段(取决于俱乐部的数量)用户)。
我在将表数据保存到另一个 Firestore 集合 RevenueReports 时遇到问题。
这是检索表数据的代码:
俱乐部计数服务.ts
getClubCounts() {
return this.firestore.collection<MyData>('users').get().pipe(
map(snapshot => {
const clubCounts: any = {};
snapshot.docs.forEach(doc => {
const clubId = doc.data().clubId;
if (clubCounts[clubId]) {
this.club = doc.data().club
clubCounts[clubId]++;
} else {
clubCounts[clubId] = 1;
}
});
const clubData: ClubData[] = [];
Object.entries(clubCounts).forEach(([clubId, count]) => {
this.firestore.doc(`clubs/${clubId}`).valueChanges().subscribe((club: any) => {
clubData.push({ clubId, clubName: club.name, count });
});
});
return clubData;
}),
takeUntil(this.dataReadySubject)
);
}
然后在组件中:
clubCounts$: any;
ngOnInit(): void {
this.clubCounts$ = this.myDS.getClubCounts();
}
在 html 中:
<table
class="table rounded-3 border-dark table-light table-sm table-striped table-hover table-bordered caption-top animate shadow table-responsive">
<thead class="table-dark">
<tr>
<th>Club Name</th>
<th>Count</th>
<th>Club Yearly</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let club of clubCounts$ | async">
<td>{{ club.clubName}}</td>
<td>{{ club.count }}</td>
<td>{{ club.count * 2 | currency}}</td>
</tr>
</tbody>
</table>
所以问题是,如何将这些数据保存到另一个集合和文档中?
我已经尝试过这段代码:
// Function to save the clubCounts data to Firestore
saveClubCountsToFirestore(clubCounts: any) {
const dateSaved = new Date(); // You can also use serverTimestamp() if needed
// Create a document in the 'revenueReports' collection
this.afs.collection('revenueReports').add({
dateSaved,
clubCounts, // Assuming 'clubCounts' contains your data fetched from 'getClubCounts()'
})
.then(() => {
console.log('ClubCounts data saved to Firestore.');
})
.catch(error => {
console.error('Error saving clubCounts data to Firestore:', error);
});
}
// Event handler for the button click
onButtonClick() {
// Access your clubCounts data from the 'clubCounts$' observable
this.clubCounts$.subscribe((clubCountsData: ClubData) => {
// Save the clubCounts data to Firestore
this.saveClubCountsToFirestore(clubCountsData);
});
}
但是,它只保存一个空数组和一个时间戳字段。
分辨率:
创建变量clubData[] = [];
然后在服务中:
const clubData: ClubData[] = []; // remove this line
Object.entries(clubCounts).forEach(([clubId, count]) => {
this.firestore.doc(`clubs/${clubId}`).valueChanges().subscribe((club: any) => {
this.clubData.push({ clubId, clubName: club.name, count });
});
});
return this.clubData;
}),
最后在保存到Firestore的功能中:
// Save club counts data to Firestore
saveClubCountsToFirestore() {
const dateSaved = serverTimestamp();
return this.firestore.collection('revenueReports').add({
dateSaved,
clubCountsData: this.clubData as any[], // Use the stored data
});
}
记录按预期保存为数组/映射。