在Firebase查询时,使用startAfter进行分页查询时,可能会出现不符合预期的结果。解决这个问题的方法是在查询请求中指定排序规则。以下是一个在Angular Firebase中实现分页查询的示例代码:
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { map } from 'rxjs/operators';
interface Item {
id: string;
name: string;
}
@Component({
selector: 'app-root',
template: `
- {{ item.name }}
`
})
export class AppComponent {
private itemsCollection = this.db.collection- ('items', ref => ref.orderBy('name'));
private lastVisible: any = null;
private firstVisible: any = null;
items = [];
constructor(private db: AngularFireDatabase) {}
ngOnInit() {
this.getItems();
}
private getItems(startAfter?: any) {
let query = this.itemsCollection.ref.limit(3);
if (startAfter) {
query = query.startAfter(startAfter);
}
query.get().then(snapshot => {
this.items = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
this.lastVisible = snapshot.docs[snapshot.docs.length - 1];
this.firstVisible = snapshot.docs[0];
});
}
previous() {
this.getItems(this.firstVisible);
}
next() {
this.getItems(this.lastVisible);
}
}
请注意,在此示例中,我们指定按照“name”属性进行排序。在查询中指定排序规则将解决使用startAfter进行分页查询时出现的不符合预期的问题。