本文介绍了如何在 Angularfire2 Angular2 中对 FirebaseListObservable 列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Firebase 实时数据库中获取所有用户并按分数属性对他们进行排序.我有这个使用变量工作
用户:FirebaseListObservable;
但我收到错误:

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[]>'.

如果我将变量更改为
users: Observable;
然后错误消失了,但是我不能使用像 .push().update() 这样的 Angularfire 方法.

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!

推荐答案

FirebaseListObservable 实现了 lift,所以 RxJS 操作符 - 比如 map - 将返回一个 FirebaseListObservable 实例.

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

只是 - 当使用 TypeScript 时 - RxJS 操作符被静态类型化以返回 Observable,所以你必须转换为 FirebaseListObservable.(使用 RxJS 不必涉及 TypeScript,如果您查看 添加操作符的指南 你会看到没有提到类型.)

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.)

您可以通过查找您在问题中提到的 pushupdate 函数来验证是否返回了 FirebaseListObservable 实例:

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());

但是请注意,这不适用于作为查询创建的 FirebaseListObservable 实例.有一个关于此类实例的尚未回答的问题.

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.

这篇关于如何在 Angularfire2 Angular2 中对 FirebaseListObservable 列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:25