【问题标题】:Descending orderByChild() on firebase and Ionic 2firebase 和 Ionic 2 上的降序 orderByChild()
【发布时间】:2017-12-02 12:10:49
【问题描述】:

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

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 网络中未解释的降序。

我需要哪些查询?

【问题讨论】:

  • Firebase 数据库始终按升序排列查询结果。没有办法用运算符反转它们。解决此限制的两种方法:1)在客户端反转列表,2)添加具有反转值的属性(例如-1 * timestamp)并对其进行排序。见stackoverflow.com/questions/25611356/…

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


【解决方案1】:

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

posts.component.ts

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

然后,您可以使用reverse 方法来反转您的帖子在模板中的顺序:

posts.component.html

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

【讨论】:

  • 如果有分页怎么办!这将不起作用,因为它只会反转第一页而不是整个列表
【解决方案2】:

ngFor

中不使用异步工作

posts.component.ts

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

然后,您可以使用 reverse 方法来反转您的帖子在模板中的顺序:

posts.component.html

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      您还应该使用 limitTolast() 而不是 limitToFirst() 来确保您的数组将从与您的数据库中的过滤器匹配的最后一个值开始(默认情况下过滤器是递增顺序),然​​后在您的数组反转它的顺序:

      1 - 让数组 = db.list('/posts')ref => ref.orderByChild('date').limitToLast(5);

      array = array.reverse();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 2020-12-26
        • 1970-01-01
        • 2021-09-17
        • 2017-12-14
        相关资源
        最近更新 更多