【问题标题】:Angular Firebase query is executed multiple times多次执行 Angular Firebase 查询
【发布时间】:2021-01-27 21:36:25
【问题描述】:

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

}

提前感谢您的帮助

【问题讨论】:

    标签: javascript angular typescript firebase


    【解决方案1】:

    你可以这样处理。

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

    【讨论】:

    • 我已经按照您所说的进行了调整。但是,问题仍然存在。似乎是 Firebase 调用,而不是 ngOnInit 的问题。有没有办法修复 FIrebase 上的这个错误?
    猜你喜欢
    • 2016-01-23
    • 2020-12-01
    • 2019-06-19
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2017-11-25
    • 2019-06-29
    相关资源
    最近更新 更多