簡體   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