[英]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.