【发布时间】:2020-12-01 09:54:38
【问题描述】:
所以,我在 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();
}
结果:这是每一步输出到控制台的内容
- 我在主页上打开应用程序(如预期的 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 行?
【问题讨论】:
-
您是否使用 Firestore SDK 启用了持久性?
-
嗨@DougStevenson,你能详细说明一下吗?这到底是什么意思?
-
不,我没有启用它。
-
它应该自动发生,但可能会清除 OnDestroy(); 中的数据数组;我假设来自 Firestore 的数据是通过服务获得的,并且它们很可能是主模块中的单例,因此它们在整个应用程序中保持活跃。
标签: javascript angular typescript firebase google-cloud-firestore