如何停止角度6 Firestore监听器

时间:2019-06-21 09:02:16

标签: angular firebase google-cloud-firestore

 ngOnInit() {    

        this.firestore.collection('mycollection').ref.where("myfiled","==","animal") 

            .onSnapshot((data=>{}));
}

这是我的代码,如果我访问其他页面,它将多次运行
例如,上面的代码在第1页中,如果我访问第2页然后返回到第1页,那么它将调用2次;如果访问第3页并返回到第一页,则它将调用3次。
如何解决?< / p>


2 个答案:

答案 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方法中取消订阅