繁体   English   中英

Angular Firebase 查询多次执行

[英]Angular Firebase query is executed multiple times

我目前在我的项目中有一个错误,我的 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);
      }
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM