因此,我有一个托管在 Firebase 上的 Angular 9 应用程序,并使用 Firestore 存储数据。我有一个看起来很简单的问题,但我无法理解为什么会发生这种情况。我已经对应用程序进行了很多简化,以找到此问题的根本原因,并将尽力在下面解释该问题。
The app:我有 2 个页面,一个主页和一个交易页面。两个页面都从同一个 Firebase 集合“交易”中读取。但是,在主页上,我想显示 4 个最近的交易(按日期降序排序),而在交易页面上我想显示 10 个最赚钱的交易(按金额降序排序)。目前,我只是将数据记录到控制台进行调试。在记录数据之前,我还对其进行了一些轻微的操作(请参阅下面的代码)。
问题:当我启动主页时,我可以在控制台中按预期看到我最近的 4 笔交易。然而,当我进入“交易”页面时,它会再次在控制台中记录 4 个最近的交易,这些交易应该只显示在主页上。大约一秒钟后,它会显示预期的 10 笔最赚钱的交易。
The code:
这是我的 home.page.ts 代码:
txSubscription: Subscription;
constructor(
public afAuth: AngularFireAuth,
private readonly firestore: AngularFirestore
) { }
// Function to get the 4 most recent transactions
async getRecentTransactions() {
this.txSubscription = this.firestore
.collection('transactions', ref => ref.orderBy('date', 'desc').limit(4))
.valueChanges()
.subscribe(rows => {
this.recentTransactions = [];
rows.forEach(row => {
let jsonData = {};
jsonData['ticker'] = (row['ticker'].length <= 10 ? row['ticker'] : row['ticker'].substring(0, 10) + '...');
jsonData['date'] = formatDate(row['date'].toDate(), 'dd/MM/y', 'en');
jsonData['amount'] = prefix + formatNumber(row['netAmount'], 'be', '1.2-2');
this.recentTransactions.push(jsonData);
})
console.log("home page", this.recentTransactions);
})
}
ngOnInit() {
this.afAuth.onAuthStateChanged(() => {
this.getRecentTransactions();
})
}
ngOnDestroy() {
this.txSubscription.unsubscribe();
}
transaction.page.ts 的代码非常相似:
txSubscription: Subscription;
constructor(
public afAuth: AngularFireAuth,
private readonly firestore: AngularFirestore
) { }
// Function to load the data for the home page
loadHomeData() {
this.txSubscription = this.firestore
.collection('transactions', ref => ref.orderBy('profitEur', 'desc').limit(10))
.valueChanges()
.subscribe(rows => {
this.resultRows = [];
rows.forEach(row => {
this.resultRows.push(row['ticker'].slice(0, 8));
});
console.log("transaction page", this.resultRows);
})
}
ngOnInit() {
this.afAuth.onAuthStateChanged(() => {
this.loadHomeData();
})
}
ngOnDestroy() {
this.txSubscription.unsubscribe();
}
结果:这是每一步输出到控制台的内容
- 我在主页上打开应用程序(如预期 4 行):
home page (4) [{…}, {…}, {…}, {…}]
0: {ticker: "BAR", date: "21/07/2020", amount: "- € 1 086,10"}
1: {ticker: "ASL C340.0...", date: "18/07/2020", amount: "€ 0,00"}
2: {ticker: "ASL C340.0...", date: "14/07/2020", amount: "- € 750,85"}
3: {ticker: "TUI C7.00 ...", date: "20/06/2020", amount: "€ 0,00"}
length: 4
__proto__: Array(0)
- 我导航到交易页面:
transaction page (4) ["TUI C7.0", "ASL C340", "BAR", "ASL C340"]
transaction page (10) ["ASL C240", "ASL C232", "REC", "ASL C270", "ASL C310", "ASML", "ASL P220", "BAR", "CFEB", "MELE"]
为什么导航到主页时,控制台中再次显示主页中相同的 4 行?