在使用startAfter进行分页查询时,需要同时指定orderBy条件和startAfter的值。下面是一个示例代码,用于按照时间戳倒序排列并分页查询文章列表:
import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Component({
selector: 'app-article-list',
template: `
-
{{ article.title }}
`,
})
export class ArticleListComponent {
private limit = 10;
private lastVisible: any = null;
private articlesCollection: AngularFirestoreCollection;
public articles: Observable;
constructor(private afs: AngularFirestore) {
this.articlesCollection = afs.collection('articles', ref => ref.orderBy('timestamp', 'desc').limit(this.limit));
this.articles = this.articlesCollection.valueChanges({idField: 'id'});
}
loadMore() {
this.articlesCollection = this.afs.collection('articles', ref =>
ref
.orderBy('timestamp', 'desc')
.startAfter(this.lastVisible)
.limit(this.limit)
);
this.articles = this.articlesCollection.valueChanges({ idField: 'id' });
this.articles.subscribe(data => {
const lastItem = data[data.length - 1];
this.lastVisible = lastItem ? lastItem.timestamp : null;
});
}
}
在上述代码中,使用startAfter进行分页查询时,指定了orderBy条件(按照时间戳倒序排列)和startAfter的值(上一次查询的最后一条数据的时间戳)。在loadMore方法中会根据上一次查询的结果来更新lastVisible的值,以便下一次查询时使用。