有没有办法保留同一集合的引用,但使用 firestore 更改顺序?
TLDR:这就像我想要实现的功能:https://stackoverflow.com/a/17320018 https://stackoverflow.com/a/17320018,
但由于我的数据来自 firestore,我还没有完全弄清楚动态完成此操作的正确方法。
说我有一个messagesService.ts
其中包含消息集合和对消息 Observable 的引用:
messagesCollection: AngularFirestoreCollection<Message>
messages: Observable<Message[]>;
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy('dateCreated', 'desc');
});
this.messages= this.messagesCollection.valueChanges();
当我将此数据弹出到*ngFor="let message of messages | async"
它按预期在顶部显示最新消息。
我需要帮助的地方:
我希望能够单击按钮并更改消息的顺序(或从 firestore 获取的数据的顺序)。例如,您可以单击按钮按最喜欢的消息、最高浏览次数或最旧的消息、字母顺序等进行排序。我是否需要为同一集合的每种排序方式提供单独的参考?这看起来很草率,有没有更干净的方法来动态地执行此操作?
最初,我尝试了这样的事情:
sortMessagesBy(field) {
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy(field, 'desc');
});
}
但是,这不起作用,因为它似乎更改了对集合的引用,因此可观察的消息没有更新。
接下来,我尝试了这个:
sortMessagesBy(field) {
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy(field, 'desc');
});
this.messages= this.messagesCollection.valueChanges();
return this.messages;
}
但这似乎创建了一个新的 this.messages 对象,这使得 ngFor 重新渲染整个页面并且看起来非常草率(即使使用 trackBy 时也是如此)。
最终,我想进一步缩小范围,在同一个集合中,我什至可以有一个 where 子句来定位特定的消息子集,并且也能够应用相同的动态排序,即:
this.messagesCollection = this.db.collection('messages', ref => {
return ref.where("type", "==", "todo").orderBy(field, 'desc');
});
我只是不知道如何在不弄清楚如何动态地做到这一点的情况下做到这一点。