Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularFirestore Collection orderBy with snapShotChanges method

I have below code in an Angular application which is using AngularFire2.

TypeScript:

constructor(db: AngularFirestore) {
    this.booksCollectionRef = db.collection<Book>('books');

    this.books = this.booksCollectionRef.snapshotChanges().map(actions => {
        return actions.map(action => {
            const data = action.payload.doc.data() as Book;
            const id = action.payload.doc.id;
            return { id, ...data };
        });
    });
}

HTML:

<md-list>
    <md-list-item *ngFor="let book of books | async">
        <h4 md-line>{{book.name}}</h4>
    </md-list-item>
</md-list>

This code retrieves and binds data as expected (removes items when collection updated), now I want to sort the collection by a given column. I tried to use firebase orderBy clause, but I can not figure out how to use it with snapShotChanges() method.

like image 867
Nalaka526 Avatar asked Oct 08 '17 05:10

Nalaka526


2 Answers

The following should work for your use case:

this.booksCollectionRef = db.collection<Book>('books', ref => ref.orderBy('order field'));

Take a look at the documentation of AngularFirestore for further information on this topic.

like image 57
alex kucksdorf Avatar answered Nov 08 '22 03:11

alex kucksdorf


this.announcementCollectionRef = afs.collection<Announcement>('announcements', ref => ref.orderBy('createdAt', 'desc'));
this.announcements = this.announcementCollectionRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as AnnouncementId;
        const id = a.payload.doc.id;
        return { id, ...data };
    });
});
like image 38
Clayton Allen Avatar answered Nov 08 '22 02:11

Clayton Allen