Volodymyr Humeniuk
Volodymyr Humeniuk

Reputation: 3791

Order async objects by date

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() }));
    });
  }

Upvotes: 1

Views: 474

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599491

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

Upvotes: 1

Related Questions