【问题标题】:Using AngularFirestore Collection orderBy with snapShotChanges method使用带有 snapShotChanges 方法的 AngularFirestore Collection orderBy
【发布时间】:2018-03-19 13:43:09
【问题描述】:

我在使用 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.books = this.booksCollectionRef.orderBy('name','desc').snapshotChanges().map(actions =&gt;
  • @GalBracha 也不起作用。 Property 'orderBy' does not exist on type 'AngularFirestoreCollection&lt;Book&gt;'
  • 你试过TypeScript默认的sort()函数吗?如果不是,请向我们提供您的this.books 的结构。
  • @GhassenLouhaichi,还没有。那将是我的最后一个选择。但我试图在 'snapshotChanges()' 中完成这项工作,因为我可能需要类似地在 firestore 集合中使用一些其他功能。
  • 我没有关注,如果您在调用snapshotChanges() 之后使用.map,您不能简单地通过.sort 调用来对结果进行排序吗?

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


【解决方案1】:

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

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

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

【讨论】:

  • 但是我找不到将ref.orderBy 方法与snapShotChanges 方法一起使用的方法,请给我一个示例代码...
  • 如果您将构造函数中的第一行替换为我发布的行,它应该可以工作。查看我链接页面底部的示例应用程序,他们将这种方法与 valueChanges() 结合使用
  • 您是否将 orderBy('order field') 更改为您要订购的图书的正确字段?
  • 对不起...我又试了一次,它成功了。前一天我错过了一些东西...非常感谢:)
  • 很高兴为您提供帮助! ;)
【解决方案2】:

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

以下代码适用于我:

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

【讨论】:

  • 你知道为什么它对我说“属性 'forEach' 在类型 '(options?: SnapshotListenOptions) => DocumentChange[]' 上不存在。”请问?
【解决方案3】:
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 };
    });
});

【讨论】:

  • 救命稻草。这段代码对我有用,包括 ionic、angular2fire 和 firestore。
  • 如果您不订阅 DocumentChangeAction 观察者,这应该如何工作?
猜你喜欢
  • 1970-01-01
  • 2019-05-25
  • 2018-04-20
  • 2019-08-25
  • 2018-03-22
  • 2022-08-11
  • 2021-11-18
  • 1970-01-01
  • 2021-09-26
相关资源
最近更新 更多