对query 选项使用 observables 是行不通的。底层 SDK 中没有动态修改查询的 limitToFirst 的功能,并且在 AngularFire2 中也无法做到这一点。
每次可观察的 query 选项发出一个新值时,都会创建一个新的 Firebase ref。你可以在source here看到它。
但是,可以通过执行以下操作来创建一个表示无限列表的 observable:
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import rxjs/add/observable/defer";
import rxjs/add/observable/zip";
import rxjs/add/operator/concatMap";
import rxjs/add/operator/filter";
import rxjs/add/operator/first";
import rxjs/add/operator/map";
import rxjs/add/operator/scan";
import rxjs/add/operator/share";
import rxjs/add/operator/startWith";
const pageSize = 100;
let notifier = new Subject<any>();
let last: Observable<any>;
let infiniteList = Observable
// Use zip to combine the notifier's emissions with the last
// child value:
.zip(notifier, Observable.defer(() => last))
// Use concatMap to emit a page of children into the
// composed observable (note that first is used to complete
// the inner list):
.concatMap(([unused, last]) => this.af.database.list("quests", {
query: {
// If there is a last value, start at that value but ask
// for one more:
limitToFirst: last ? (pageSize + 1) : pageSize,
orderByChild: "date_published",
startAt: last
}
})
.first()
)
// Use scan to accumulate the page into the infinite list:
.scan((acc, list) => {
// If this isn't the initial page, the page was started
// at the last value, so remove it from the beginning of
// the list:
if (acc.length > 0) {
list.shift();
}
return acc.concat(list);
}, [])
// Use share so that the last observable (see below) doesn't
// result in a second subscription:
.share();
// Each time a page is emitted, map to its last child value so
// that it can be fed back into the composed infinite list:
last = infiniteList
.filter((list) => list.length > 0)
.map((list) => list[list.length - 1].date_published)
.startWith(null);
infiniteList.subscribe((list) => console.log(list));
// Each time the notifier emits, another page will be retrieved
// and added to the infinite list:
notifier.next();
notifier.next();
notifier.next();
这可行,但如果您订购的子项具有重复值,AngularFire2 将无法可靠地翻阅结果,直到重新打开并解决 this issue。
结果列表是静态的。也就是说,如果数据库发生变化,已经分页到列表中的孩子不会被更新。实现动态列表更具挑战性,因为重复和丢失的孩子很容易受到基于限制的分页机制的影响。
自从撰写此答案以来,我已经在我开源的 Firebase 可观察对象库中提供了经过测试的正向和反向、非实时和实时无限列表可观察对象的实现。见this GitHub repo。