Descending orderByChild() on firebase and Ionic 2

Issue

I need get items sorted by date, but obviously I need descending sorted to show the posts in correct order…

import {
  AngularFireDatabase
} from 'angularfire2/database';
import 'rxjs/add/operator/map';

/*
  Generated class for the FirebaseProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FirebaseProvider {

  constructor(public afd: AngularFireDatabase) {}


  getPostsItems() {
    return this.afd.list('/Posts/', {
      query: {
        orderByChild: "date",
      }
    });

  }

This query returns a ascendent order and I need a descendent order that it’s not explained in Firebase web.

Which are queries I need?

Solution

One approach could be reversing the order in your component’s template. First, you get a list of posts directly in your component:

posts.component.ts

    export class PostsComponent {
      posts: FirebaseListObservable<any>;
     
      constructor(db: AngularFireDatabase) {
        this.posts = db.list('/posts', {
          query: {
            orderByChild: 'date'
          }
        });
      }
    }

Then, you can use the reverse method to reverse your posts’ order in your template:

posts.component.html

    <div *ngFor="let post of (posts | async)?.slice().reverse()">
      <h1>{{ post.title }}</h1>
    </div>

Answered By – Will

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published