ngOnInit() {
this.firestore.collection('mycollection').ref.where("myfiled","==","animal")
.onSnapshot((data=>{}));
}
这是我的代码,如果我访问其他页面,它将多次运行
例如,上面的代码在第1页中,如果我访问第2页然后返回到第1页,那么它将调用2次;如果访问第3页并返回到第一页,则它将调用3次。
如何解决?< / p>
答案 0 :(得分:2)
首先在您的组件中实施OnDestroy
。更改页面时,将调用ngOnDestroy
。
然后您可以像这样退订:
this.unsubscribe = this.firestore.collection("mycollection")
.ref.where("myfiled","==","animal")
.onSnapshot((data=>{
// Your code
}));
在ngOnDestroy
中:
ngOnDestroy() {
// Stop listening to changes
this.unsubscribe();
}
检查the documentation了解更多信息。
答案 1 :(得分:-1)
firestore.collection
为您提供了unsubscribe
方法。只需将此代码分配给变量,然后在OnDestroy方法中取消订阅