gpt4 book ai didi

angular - Firestore + AngularFire2 分页(按范围查询项目 - .startAfter(lastVisible) )

转载 作者:太空狗 更新时间:2023-10-29 18:18:59 24 4
gpt4 key购买 nike

在一个组件中,我想从 FireStore 中提取一系列项目,例如。从 0 到 5,从 5 到 10 等等。我找到了 this在 FireStore 的文档中,但他们不使用 AngularFire2,所以我更加努力地尝试重构,因为我得到了更大的困惑。我通过简单的 splice() 使它工作'ing:

service ->

topFirstScores(): AngularFirestoreCollection<Score> {
return this.fireRef.collection('scores', r => r
.orderBy('score', 'desc').limit(6)
);
}

component ->

$scores = new Subject();

this.scores$ = this.$scores.asObservable();
if (this.scores === 'first') {
this.scoreS.topFirstScores().valueChanges().take(1)
.subscribe(_ => this.$scores.next(_.splice(0, 3)))
} else {
this.scoreS.topFirstScores().valueChanges().take(1)
.subscribe(_ => this.$scores.next(_.splice(3, 3)))
}

但这似乎更像是一种解决方法。谁能翻译一下:

var first = db.collection("cities")
.orderBy("population")
.limit(25);

return first.get().then(function (documentSnapshots) {
// Get the last visible document
var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
console.log("last", lastVisible);

// Construct a new query starting at this document,
// get the next 25 cities.
var next = db.collection("cities")
.orderBy("population")
.startAfter(lastVisible)
.limit(25);
});

最好返回 AngularFirestoreCollection<T>

最佳答案

我遇到了同样的问题,这就是我所做的。

服务

private _data: BehaviorSubject<Scores[]>;
public data: Observable<Scores[]>;
latestEntry: any;

constructor(private afs: AngularFirestore) {}

// You need to return the doc to get the current cursor.
getCollection(ref, queryFn?): Observable<any[]> {
return this.afs.collection(ref, queryFn).snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
const doc = a.payload.doc;
return { id, ...data, doc };
});
});
}
// In your first query you subscribe to the collection and save the latest entry
first() {
this._data = new BehaviorSubject([]);
this.data = this._data.asObservable();

const scoresRef = this.getCollection('scores', ref => ref
.orderBy('score', 'desc')
.limit(6))
.subscribe(data => {
this.latestEntry = data[data.length - 1].doc;
this._data.next(data);
});
}

next() {
const scoresRef = this.getCollection('scores', ref => ref
.orderBy('scores', 'desc')
// Now you can use the latestEntry to query with startAfter
.startAfter(this.latestEntry)
.limit(6))
.subscribe(data => {
if (data.length) {
// And save it again for more queries
this.latestEntry = data[data.length - 1].doc;
this._data.next(data);
}
});
}

组件

  scores$: Observable<Scores[]>;
...
ngOnInit() {
this.yourService.first();
this.scores$ = this.yourService.data;
}

nextPage() {
this.yourService.next();
}

关于angular - Firestore + AngularFire2 分页(按范围查询项目 - .startAfter(lastVisible) ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49536684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com