在firebase和Ionic 2上降序orderByChild()

时间:2017-06-28 23:39:45

标签: sorting firebase ionic-framework firebase-realtime-database ionic2

我需要按日期排序项目,但显然我需要降序排序以正确的顺序显示帖子...

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",
      }
    });

  }

此查询返回一个上升顺序,我需要一个后代订单,它在Firebase网站中没有解释。

我需要哪些查询?

3 个答案:

答案 0 :(得分:5)

一种方法可能是颠倒组件模板中的顺序。首先,您可以直接在组件中获得帖子列表:

<强> posts.component.ts

export class PostsComponent {
  posts: FirebaseListObservable<any>;

  constructor(db: AngularFireDatabase) {
    this.posts = db.list('/posts', {
      query: {
        orderByChild: 'date'
      }
    });
  }
}

然后,您可以使用reverse方法撤消帖子&#39;在模板中订购:

<强> posts.component.html

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

答案 1 :(得分:1)

将此留给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>

答案 2 :(得分:0)

ngFor

中不使用异步工作

<强> posts.component.ts

export class PostsComponent {
posts: FirebaseListObservable<any>;

constructor(db: AngularFireDatabase) {
 this.posts = db.list('/posts', {
   query: {
     orderByChild: 'date'
   }
 });
}
} 

然后,您可以使用反向方法来反转您的帖子&#39;在模板中订购:

<强> posts.component.html

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