How can I sort a FirebaseListObservable list in Angularfire2 Angular2?

这一生的挚爱 提交于 2019-12-10 19:22:17

问题


I want to get all users from a Firebase realtime database and sort them by a score property. I've got this to work using the variable
users: FirebaseListObservable<any[]>;
but I get the errors:

Type 'Observable<any[]>' is not assignable to type 'FirebaseListObservable<any[]>'.
Property '_ref' is missing in type 'Observable<any[]>'.

If I change the variable to
users: Observable<any[]>;
then the errors go away, but then I can't use the Angularfire methods like .push() and .update().

My fetching and sorting code (which works) looks like:

this.users = this.af.database.list('/users')
  .map(items => items.sort((a, b) => b.score - a.score));

I would appreciate any advice on how this should be done to avoid the errors, or any preferred way, thank you!


回答1:


The FirebaseListObservable implements lift, so RxJS operators - like map - will return a FirebaseListObservable instance.

It's just that - when using TypeScript - the RxJS operators are statically typed to return Observable, so you have to cast to FirebaseListObservable. (Using RxJS does not have to involve TypeScript and if you look at the guidance for adding operators you will see that types are not mentioned.)

You can verify that a FirebaseListObservable instance is returned by looking for the push and update functions you mentioned in your question:

this.users = this.af.database
  .list('/users')
  .map(items => items.sort((a, b) => b.score - a.score)) as FirebaseListObservable<any[]>;
console.log(this.users.push.toString());
console.log(this.users.update.toString());

Note, however, that this will not work for FirebaseListObservable instances that are created as queries. There is an as-yet-unanswered question regarding such instances.




回答2:


You need this example. To watch other opts see Query interface.

this.items = angularFire.database.list('/users', {
  query: {
    orderByChild: 'childPropertyName'
  }
});

export interface Query {
    [key: string]: any;
    orderByKey?: boolean | Observable<boolean>;
    orderByPriority?: boolean | Observable<boolean>;
    orderByChild?: string | Observable<string>;
    orderByValue?: boolean | Observable<boolean>;
    equalTo?: any | Observable<any>;
    startAt?: any | Observable<any>;
    endAt?: any | Observable<any>;
    limitToFirst?: number | Observable<number>;
    limitToLast?: number | Observable<number>;
}


来源:https://stackoverflow.com/questions/39133217/how-can-i-sort-a-firebaselistobservable-list-in-angularfire2-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!