使用 AngularFirestore 集合 orderBy 和 snapShotChanges 方法

Using AngularFirestore Collection orderBy with snapShotChanges method

我在使用 AngularFire2 的 Angular 应用程序中有以下代码。

打字稿:

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>

此代码按预期检索和绑定数据(在集合更新时删除项目),现在我想按给定列对集合进行排序。我尝试使用 firebase orderBy 子句,但我不知道如何使用 snapShotChanges() 方法。

以下应该适用于您的用例:

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

查看 documentation of AngularFirestore 了解有关此主题的更多信息。

不确定 Angular Fire,但您可以尝试直接使用 Firebase Firestore 库。

以下代码适用于我:

someCollectionRef
.orderBy('columnName')
.onSnapshot((snapshot) => {
snapshot.docChanges.forEach(function (change) {
...doStuff
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 };
    });
});