Descending orderByChild() on firebase and Ionic 2

2019-04-12 13:00发布

问题:

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?

回答1:

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>


回答2:

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>


回答3:

Working without async in the ngFor

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?.slice().reverse()">
<h1>{{ post.title }}</h1>
</div>