[英]How to stop angular 6 firestore listener
ngOnInit() {
this.firestore.collection('mycollection').ref.where("myfiled","==","animal")
.onSnapshot((data=>{}));
}
這是我的代碼,如果我訪問其他頁面,它將運行多次
例如,上面的代碼在 page1 中,如果我訪問 page2 然后返回到 page1,那么它將調用 2 次,如果訪問 page3 並返回到第一頁,它將調用 3 次。
如何解決?
首先在您的組件中實現OnDestroy
。 更改頁面時將調用ngOnDestroy
。
然后,您可以像這樣退訂:
this.unsubscribe = this.firestore.collection("mycollection")
.ref.where("myfiled","==","animal")
.onSnapshot((data=>{
// Your code
}));
在ngOnDestroy
:
ngOnDestroy() {
// Stop listening to changes
this.unsubscribe();
}
查看文檔以獲取更多信息。
我花了一些時間直到我在 angular 和 firestore 9 中弄明白了。這是完整的代碼:
unsubscribe: any = null
ngOnDestroy() {
// Stop listening to changes
this.unsubscribe();
}
startListening() {
// some code to configure listening here
if (this.unsubscribe() != null) { // I detach listener and attach it again
this.unsubscribe()
}
this.unsubscribe = onSnapshot(query, (snapshot) => {
// code processing changes in collection
})
}
在我的例子中,我需要更改監聽器的參數。 這就是為什么我在 startListening() 中再次分離並附加偵聽器的原因
firestore.collection
提供了unsubscribe
方法。 只需將此代碼分配給變量,然后在OnDestroy方法中取消訂閱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.