Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Descending orderByChild() on firebase and Ionic 2

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?

like image 817
nfont Avatar asked Dec 23 '22 16:12

nfont


2 Answers

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>
like image 151
Will Avatar answered Dec 26 '22 06:12

Will


Leaving this for Ionic 3 + AngularFire 4

posts.component.ts

    import { AngularFireDatabase } from 'angularfire2/database';
    export class PostsComponent {
          posts;
    
      constructor(db: AngularFireDatabase) {
        this.posts = db.list('/posts', ref => ref.orderByChild('date')).valueChanges();
      }
    }

posts.component.html

     <div *ngFor="let post of (posts | async)?.slice().reverse()">
      <h1>{{ post.title }}</h1>
    </div>
like image 34
Nicholas Ibarra Avatar answered Dec 26 '22 06:12

Nicholas Ibarra