简体   繁体   中英

Angular Firebase query is executed multiple times

I currently have a bug within my project where my Firebase queries are being executed multiple times. This problem was not around throughout my development and nothing has been changed with relation to Firebase dependencies etc

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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