使用AngularFirestore Collection orderBy和snapShotChanges方法

时间:2017-10-08 05:52:37

标签: angular typescript firebase angularfire2 google-cloud-firestore

我在使用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()方法一起使用。

3 个答案:

答案 0 :(得分:22)

以下内容适用于您的用例:

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

请查看documentation of AngularFirestore以获取有关此主题的更多信息。

答案 1 :(得分:5)

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 :(得分:0)

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

以下代码适用于我:

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