简体   繁体   中英

AngularFire - Push data from firestore collection query into an array

I'm querying a Firestore collection an successfully retrieving the results. 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

<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. Instead of only pushing the array and never empty it.

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