首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Firebase查询被多次执行

问Angular Firebase查询被多次执行
EN

Stack Overflow用户
提问于 2021-01-28 05:36:26
回答 1查看 32关注 0票数 0

我目前在我的项目中有一个bug,我的Firebase查询被多次执行。这个问题在我的整个开发过程中都没有出现,与Firebase依赖等相关的内容也没有发生任何变化

下面是一段示例代码,它过去只执行一次,但现在执行了多次

代码语言:javascript
复制
  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);
}

}

提前感谢您的帮助

EN

回答 1

Stack Overflow用户

发布于 2021-01-28 23:46:45

你可以像这样处理。

代码语言:javascript
复制
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);
      }
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65927764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档