Aayush Gupta
Aayush Gupta

Reputation: 502

How to sort data fetching from cloud firestore

I am using a service to fetch the data from my firestore collection and now what i want to do is to sort the documents by one of the fields say "date" Attaching codes below:

BARCODE.SERVICE.TS

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Barcode } from '../models/barcode';
@Injectable({
  providedIn: 'root'
})
export class BarcodeService {
  barcodesCollection: AngularFirestoreCollection<Barcode>;
  barcodes: Observable<Barcode[]>;
  constructor(public afs: AngularFirestore) { 
    this.barcodesCollection = this.afs.collection('barcodes');

    this.barcodes = this.barcodesCollection.valueChanges();
  }
  getBarcodes(){
    this.barcodes = this.afs.collection('barcodes').valueChanges();
    return this.barcodes;
  }

  addBarcode(barcode: Barcode) {
    this.barcodesCollection.add(barcode);
  }
}

COMPONENT.TS (only showing required part)

ngOnInit() {
    this.barcodeService.getBarcodes().subscribe(barcodes => {
      this.barcodes = barcodes;
    });
  }

COMPONENT.HTML

<div *ngIf="barcodes.length > 0;else noBarcodes">
        <div *ngFor="let barcode of barcodes">
            <a (click)="viewdet(barcode.id)"><table >
                    <tr>
                        <td><h3 class="big"><b>{{barcode.vendor}}</b></h3></td>
                        <td rowspan="3"><span>&#8250;</span></td>
                    </tr>
                    <tr>
                        <td><h3><b>Reel No:</b> {{barcode.reelno}}</h3></td>
                    </tr>
                    <tr>
                        <td><h3><b>Date:</b> {{barcode.date}}</h3></td>
                    </tr>


            </table></a>
        </div>
    </div>

Upvotes: 0

Views: 89

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

According to the documentation, the following should work (not tested however):

  getBarcodes(){
    this.barcodes = this.afs.collection('barcodes', ref => ref.orderBy('date')).valueChanges();
    return this.barcodes;
  }

Upvotes: 2

Related Questions