因此,我在 Firebase 上托管了一个 Angular 9 应用程序,并使用 Firestore 存储数据。我有一个看起来很简单的问题,但我无法理解它为什么会发生。我已经对应用程序进行了很多简化以找到其根本原因,并将尝试在下面尽可能解释该问题。
应用程序 : 我有 2 个页面,一个主页和一个交易页面。两个页面都从同一个 Firebase 集合“事务”中读取。但是,在主页上,我想显示最近的 4 笔交易(按日期排序,降序),而在交易页面上,我想显示 10 笔最赚钱的交易(按金额排序,降序)。目前,我只是将数据记录到控制台进行调试。在记录数据之前,我还稍微对其进行了操作(参见下面的代码)。
问题 :当我在主页上启动时,我可以在控制台中按预期看到我最近的 4 笔交易。但是,当我转到“事务”页面时,它会在短时间内再次在控制台中记录 4 个最近的事务,这些事务应该只显示在主页上。大约一秒钟后,它显示了预期的 10 笔最有利可图的交易。
代码 :
这是我的 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();
}
结果 :这是每一步输出到控制台的内容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 行?
最佳答案
您在交易页面上获得 2 次结果。很有可能valueChanges
从 firestore 内存缓存中返回数据作为快速响应,然后从真实数据中读取。在您的情况下,当它们在主页上返回时缓存 4 行,并从事务页面上的缓存中处理它们。
关于javascript - 带有 Firebase 数据的 Angular 应用程序 : why am I seeing data from the previous page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63363151/