I have a little angular application (Angular 6) with angularfire2, now i want to select only one object, odered by date, i can get .take(1) or .map() but not together, how is that done?
I tried it with the following approche
return this.db.list(this.BASE_PATH, ref => ref.orderByChild(this.PUBLISH_DATE).limitToLast(1)).snapshotChanges().pipe(take(1)).pipe(map(res => {
return res.map(item => {
console.log(item);
});
}));
take(n)
only takes the first n emissions of the observable, not n items of the array emitted, see here for more information on the take
operator.
You can just use map
to sort/filter your array and return the desired value and then subscribe. Do something like this:
this.db.list(this.BASE_PATH, ref => ref.orderByChild(this.PUBLISH_DATE).limitToLast(1)).snapshotChanges()
.pipe(map(arr => arr.sort((a, b) => b.date - a.date)[0]))
.subscribe(item => {
console.log(item);
});
EDIT: This stackblitz might do a better job of showcasing it.