There seem to be a lot of examples, tutorials and videos on howto paginate to the next page when using Angular with Cloud Firestore (Firebase).
But after extensive search i cannot find a way to paginate to a previous page. The furthest i got is just returning to the first page.
Here is how my Service looks right now:
import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Task } from './task.model';
@Injectable()
export class TaskService {
private _data: BehaviorSubject<Task[]>;
public data: Observable<Task[]>;
firstEntry: any;
latestEntry: any;
constructor(private afs: AngularFirestore) { }
public first() {
this._data = new BehaviorSubject([]);
this.data = this._data.asObservable();
const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').limit(5))
.subscribe(data => {
this.firstEntry = data[0].doc;
this.latestEntry = data[data.length - 1].doc;
this._data.next(data);
});
}
public next() {
const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').startAfter(this.latestEntry).limit(5))
.subscribe(data => {
if (data.length) {
this.firstEntry = data[0].doc;
this.latestEntry = data[data.length - 1].doc;
this._data.next(data);
}
});
}
public previous() {
const tasksRef = this.getCollection('tasks', ref => ref.orderBy('createdAt').endBefore(this.firstEntry).limit(5))
.subscribe(data => {
if (data.length) {
this.firstEntry = data[0].doc;
this.latestEntry = data[data.length - 1].doc;
this._data.next(data);
}
});
}
private getCollection(ref, queryFn?): Observable<any[]> {
return this.afs.collection(ref, queryFn).snapshotChanges().pipe(
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 };
});
})
);
}
}
The initial loading (first page) works, and also all next pages are working as expected.
But it seems like endBefore(this.firstEntry)
doesn't hold the correct cursor, and results in the first page again.
What is the proper way to navigate back to the previous page?
And if someone knows of a complete tutorial or example of a working paginator, please share...