如何解决带有Firebase数据的Angular应用程序:为什么我看到上一页中的数据?
因此,我在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",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","CFEB","MELE"]
为什么导航到主页时,它又在控制台中再次显示来自主页的相同4行?
解决方法
我认为问题出在这里:
loadHomeData() {
this.txSubscription = this.firestore
...
.subscribe(rows => {
...
})
}
ngOnInit() {
this.afAuth.onAuthStateChanged(() => {
this.loadHomeData();
})
}
ngOnDestroy() {
this.txSubscription.unsubscribe();
}
您正在正确退订。但是,看看再次触发onAuthStateChanged会发生什么。您的第一个订阅已丢失,无法取消订阅。我认为在switchmap
上使用onAuthStateChanged
运算符可以解决您的问题。像这样:
this.subscription = this.af.authState.pipe(
switchMap(auth => {
if(auth !== null && auth !== undefined){
return this.firestore.collection('transactions',ref => ref.orderBy('profitEur','desc').limit(10)).valueChanges())
} else{
throw "Not loggedin";
}
).subscribe(...)
,
您在交易页面上获得2次结果。 valueChanges
很可能从Firestore内存高速缓存中返回数据作为快速响应,然后从真实数据中读取。在您的情况下,当在首页上返回4行时会缓存它们,并从事务页面上的缓存中对其进行处理。
此问题可能是由于
this.afAuth.onAuthStateChanged()
触发两次。
代替检查每个组件上的auth状态。
您可以简单地在app.component.ts
上订阅身份验证状态。如果用户未经身份验证或身份验证状态更改,它将重定向到登录页面,否则将重定向到home.page.ts
export class AppComponent {
constructor(private readonly auth: AngularFireAuth,private router: Router) {
this.auth.authState.subscribe(response => {
console.log(response);
if (response && response.uid) {
this.router.navigate(['dashboard','home']); //Home page route
} else {
this.router.navigate(['auth','login']); //Login page route
}
},error => {
this.auth.signOut();
this.router.navigate(['auth','login']); //Login Page route
});
}
}
在home.component.ts和transaction.page.ts中,无需检查身份验证状态。
- home.component.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.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','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.loadHomeData();
}
ngOnDestroy() {
this.txSubscription.unsubscribe();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。