简体   繁体   English

Angular Firebase 查询多次执行

[英]Angular Firebase query is executed multiple times

I currently have a bug within my project where my Firebase queries are being executed multiple times.我目前在我的项目中有一个错误,我的 Firebase 查询被多次执行。 This problem was not around throughout my development and nothing has been changed with relation to Firebase dependencies etc这个问题在我的整个开发过程中都没有出现,并且与 Firebase 依赖项等相关的任何内容都没有改变

Here is an example piece of code which used to execute just once but now executes multiple times这是一个示例代码,它曾经只执行一次,但现在执行多次

  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);
}

} }

Thank you in advance for any help预先感谢您的任何帮助

You can handle like this.你可以这样处理。

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