Angular Firebase查询被执行多次



我目前在我的项目中有一个bug,我的Firebase查询正在多次执行。这个问题在我的整个开发过程中都没有出现,也没有改变与Firebase依赖关系等

这是一个示例代码,以前只执行一次,但现在执行多次

ngOnInit(): void {
this.array = [];
// Try-Catch function reading data from Firestore
try {
this.db.collection("myCollection").where("Age", "==", "20").onSnapshot(snapshot => {
snapshot.docs.forEach (() => {
this.db.collection('Jobs').get().then (snapshot2 => {
snapshot2.docs.forEach (snapshot3 => {
if (snapshot3.id.includes('Unemployed')){
this.array.push(
{
ID: snapshot3.id
}
);
}
})
})
})
})

} catch (error) {
console.log(error.message);
}

}

提前感谢您的帮助

你可以这样处理。

array: any[] = [];
ngOnInit() {
// this.array = [];  //no need to set this empty array here
// will go inside only if required array is empty
if (!this.array || !this.array.length) {
// Try-Catch function reading data from Firestore
try {
this.db
.collection("myCollection")
.where("Age", "==", "20")
.onSnapshot(snapshot => {
snapshot.docs.forEach(() => {
this.db
.collection("Jobs")
.get()
.then(snapshot2 => {
snapshot2.docs.forEach(snapshot3 => {
if (snapshot3.id.includes("Unemployed")) {
this.array.push({
ID: snapshot3.id
});
}
});
});
});
});
} catch (error) {
console.log(error.message);
}
}
}

最新更新