简体   繁体   English

AngularFire-将来自Firestore集合查询的数据推入数组

[英]AngularFire - Push data from firestore collection query into an array

I'm querying a Firestore collection an successfully retrieving the results. 我正在查询Firestore集合,成功检索了结果。 However, I'm using a sortable angular plugin that requires an array to sort. 但是,我使用的是需要数组进行排序的可排序角度插件。

The issue I have is that the items are being pushed into the array, but I cannot find a correct location to clear the array when new items come in. Without clearing the array, the results returned start to duplicate in the array. 我遇到的问题是将项目推入数组,但是当有新项目进入时,我找不到正确的位置来清除数组。如果不清除数组,返回的结果将开始在数组中重复。

Is someone able to help refactor the code below so that I can successfully push the collection results into the array and clear it in the correct spot please? 有人可以帮助重构下面的代码,以便我成功地将收集结果推入数组并在正确的位置清除它吗?

...
itemsArray = []
...

getData(){
    this.issueCollection = this.afs.collection<any>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;

        this.itemsArray.push({ id, ...data });

        return { id, ...data };
      }))
    );
  }

HTML - How I need the HTML to display the results HTML-我如何需要HTML显示结果

<ul>
   <li *ngFor="let issue of itemsArr">
      {{ issue.issueName }}
   </li>
</ul>

Update - This seems to work 更新 -这似乎有效

  getData(){
    this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('issue_order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => {
      this.itemsArr = [];
      return actions.map(a => {

        const data = a.payload.doc.data();
        const id = a.payload.doc.id;


        this.itemsArr.push({ id, ...data });


        return { id, ...data };
      });
    }))
  }

What I would do is make it subcribe to the collection and do this: 我要做的是让它订阅集合,并执行以下操作:

getData(){
    this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;

            return { id, ...data };
        }))).subscribe((items: any[]) => {
          this.itemsArray = [];
          this.itemsArray = items;
       });
  }

This will allow you to empty the itemsArray and refill it. 这将允许您清空itemsArray并重新填充它。 Instead of only pushing the array and never empty it. 而不是仅推入数组并且永远不要将其清空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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