簡體   English   中英

使用AngularFirestore Collection 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'));

有關此主題的更多信息,請查看AngularFirestore文檔

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 }; }); });

不確定Angular Fire,但您可以嘗試直接使用Firebase Firestore庫。

以下代碼適用於我:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM