在进行分页查询时,startAfter应在查询之前设置。以下是正确使用startAfter的示例代码:
import { Component } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Component({
selector: 'app-posts',
template: `
{{ post.title }}
`,
})
export class PostsComponent {
private batchSize = 5;
private lastVisible: any = null;
posts: Observable;
constructor(private afs: AngularFirestore) {
this.posts = this.afs
.collection('posts', ref => ref.orderBy('created', 'desc').limit(this.batchSize))
.valueChanges();
loadMore() {
this.afs
.collection('posts', ref => ref.orderBy('created', 'desc').startAfter(this.lastVisible).limit(this.batchSize))
.valueChanges({idField: 'id'})
.subscribe((posts: any[]) => {
if (posts.length > 0) {
this.lastVisible = posts[posts.length - 1].id;
this.posts = this.posts.pipe(map(arr => arr.concat(posts)));
}
});
}
}