1

I have Angular 5 + Firebase app, where I get items from a Firebase list and set them into a view with *ngFor.

  <a routerLink="post/{{post.url}}" *ngFor="let post of (posts | async)">
     <h2>{{ post?.title }}</h2>
     <span>{{ post?.date }}</span>
  </a>

Every item I have a "Date" field in the format "dd.mm.yyyy". How can I set them into component view sorted by date (from newest to older)?

How can I get posts from Firebase:

  getPosts(): Observable<any[]> {
    return this.db.list('posts').snapshotChanges().map(changes => {
      return changes.map(c => ({
        key: c.payload.key,
        ...c.payload.val() }));
    });
  }
Pete
  • 769
  • 7
  • 20
Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70
  • You can probably sort the `posts` when you get them. Can we see the code for that? – ConnorsFan Apr 15 '18 at 00:15
  • 1
    As @ConnorsFan says you can query from firebase and get the sorted data, if not, you can also map over the observable and sort in the service before subscribe in the template – Ricardo Apr 15 '18 at 00:24
  • @ConnorsFan i add code to question – Volodymyr Humeniuk Apr 15 '18 at 00:27
  • I don't know firebase but you can try this syntax: `this.db.list('posts', { query: { orderByChild: 'date' } }).map((arr) => { return arr.reverse(); }).snapshotChanges()...`. There may be a way to specify "desc" with `orderByChild`; if so, the call to `reverse()` would not be necessary. – ConnorsFan Apr 15 '18 at 00:41

1 Answers1

1

You have the dates as "dd.mm.yyyy", which is a date format that is inherently hard to sort. With that format, you'll have to do sorting/filtering on the client.

If you store the dates in an ISO-8859 format (e.g. yyyy-mm-dd) you can let Firebase handle the sorting/filtering with:

this.db.list('posts', ref => ref.orderByChild('date'))

See also the AngularFire2 documentation on queries.

Note that this will only sort the items in ascending order though, so from oldest to newest. If you want them descending you'll either have to reverse in the client, or store an inverted value. In the latter case I'd recommend storing an inverted timestamp instead of a string, e.g.

"negativeTimestamp": -1523753371440

For more on this, see the links in my answer to firebase -> date order reverse

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807