How to use snapshotChanges() method to get both key value and filter the data?
In my case I solved it by importing rxjs operator map, combined by .pipe
import { map } from 'rxjs/operators';
Example:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AngularFirestore } from 'angularfire2/firestore';
import { IdeaService } from './app.service';
import { config } from './app.config';
import { Idea } from './app.model';
import {
AngularFirestoreDocument,
AngularFirestoreCollection
} from 'angularfire2/firestore';
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let idea of ideas | async">
<pre>{{ idea | json }}</pre>
</li>
</ul>
`
})
export class AppComponent {
public ideasCollection: AngularFirestoreCollection<Idea>;
public ideas: Observable<any[]>;
constructor(db: AngularFirestore, private ideaService: IdeaService) {
this.ideasCollection = db.collection<Idea>(config.collection_endpoint);
this.ideas = this.ideasCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Idea;
const id = a.payload.doc.id;
return { id, ...data };
});
}));
}
}
Declare a function to add id to your Object :
documentToDomainObject = _ => {
const object = _.payload.doc.data();
object.id = _.payload.doc.id;
return object;
}
And use it in your getBooks method :
getBooks(){
this.books = this.db.list('/books').snapshotChanges()
.pipe(map(actions => actions.map(this.documentToDomainObject)));
return this.books;
}