Is there a method to maintain a reference of the same collection while altering the ordering using firestore?
TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find the right approach to accomplish this dynamically.
Imagine I have a messagesService.ts
file which holds a collection of messages and an Observable reference to these messages:
messagesCollection: AngularFirestoreCollection<Message>
messages: Observable<Message[]>;
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy('dateCreated', 'desc');
});
this.messages= this.messagesCollection.valueChanges();
When this data is displayed using
*ngFor="let message of messages | async"
, it showcases the latest messages at the top, just as expected.
Assistance Required:
I would like to implement a feature where users can click a button to change the order of messages (or the order of retrieved data from firestore). For instance, sorting messages by most likes, highest views, oldest messages, alphabetical order, etc. Do I need a separate reference for each sorting criteria? This approach seems clunky, so is there a more efficient way to accomplish this dynamically?
Initially, I attempted something like this:
sortMessagesBy(field) {
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy(field, 'desc');
});
}
However, this did not work well because it appeared to modify the reference to the collection, resulting in the messages observable not being updated.
So, I tried another approach:
sortMessagesBy(field) {
this.messagesCollection = this.db.collection('messages', ref => {
return ref.orderBy(field, 'desc');
});
this.messages= this.messagesCollection.valueChanges();
return this.messages;
}
But this creates a new this.messages object, causing ngFor to re-render the entire page, making it appear messy (even with trackBy implemented).
In the long run, I aim to delve deeper within the same collection, possibly incorporating a where clause to target specific subsets of messages while maintaining dynamic sorting capabilities, e.g.:
this.messagesCollection = this.db.collection('messages', ref => {
return ref.where("type", "==", "todo").orderBy(field, 'desc');
});
It seems challenging to achieve this without solving the dynamic sorting puzzle first.