typescript 使用 AngularFirestore Collection orderBy 和 snapShotChanges 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46627957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using AngularFirestore Collection orderBy with snapShotChanges method
提问by Nalaka526
I have below code in an Angular application which is using AngularFire2.
我在使用 AngularFire2 的 Angular 应用程序中有以下代码。
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:
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 orderByclause, but I can not figure out how to use it with snapShotChanges()
method.
此代码按预期检索和绑定数据(在集合更新时删除项目),现在我想按给定列对集合进行排序。我尝试使用 firebase orderBy子句,但我不知道如何将它与snapShotChanges()
方法一起使用。
回答by alex kucksdorf
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 AngularFirestorefor further information on this topic.
查看AngularFirestore的文档以获取有关此主题的更多信息。
回答by Clayton Allen
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 };
});
});
回答by sgt_lagrange
Not sure about Angular Fire, but you can try using the Firebase Firestore libraries directly.
不确定 Angular Fire,但您可以尝试直接使用 Firebase Firestore 库。
The following code works for me:
以下代码对我有用:
someCollectionRef
.orderBy('columnName')
.onSnapshot((snapshot) => {
snapshot.docChanges.forEach(function (change) {
...doStuff