Using AngularFirestoreBy sort order using the snapShotChanges method

I have code in an Angular application that uses 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 the data as expected (deletes items when updating the collection), now I want to sort the collection by this column. I tried using firebase orderBy , but I cannot figure out how to use it with a method snapShotChanges().

+4
source share
3 answers

In your use case, the following should work:

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

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

+10
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 };
    });
});
+2

Not sure about Angular Fire, but you can try using the Firebase Firestore libraries directly.

The following code works for me:

someCollectionRef
.orderBy('columnName')
.onSnapshot((snapshot) => {
snapshot.docChanges.forEach(function (change) {
...doStuff
0
source

Source: https://habr.com/ru/post/1687104/


All Articles