AngularFire2 Query Not Returning Document ID
I'm using AngularFire2 in a service to get data from a Firestore collection. The code looks something like this:
this.db.collection('organizations')
.valueChanges()
.pipe(first())
.toPromise()
.next(organization => console.log(organization));
The console is logging the organization object exactly as expected. But that object is lacking the id of the Firestore document.
So I'm wondering if there's something that can be done to get the ID as part of that query...
Answer
you can use the snapshot something like this:
private getOrganizations(whereClause: any): any {
return this.db.collection('organizations')
.snapshotChanges()
.pipe(
map((docs: any) => {
return docs.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return {id, ...data};
});
})
);
}
For more details about snapshotChanges
check this:
https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md#snapshotchanges
snapshotChanges()
What is it? - Returns an Observable of data as a DocumentChangeAction.
Why would you use it? - When you need the document data but also want to keep around metadata. This metadata provides you the underyling DocumentReference and document id. Having the document's id around makes it easier to use data manipulation methods. This method gives you more horsepower with other Angular integrations such as ngrx, forms, and animations due to the type property. The type property on each DocumentChangeAction is useful for ngrx reducers, form states, and animation states.What is it? - Returns an Observable of data as a
Related Questions
- → Make a Laravel collection into angular array (octobercms)
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → Angularjs not working inside laravel form
- → Analysis of Flux implementations
- → how to write react component to construct HTML DOM
- → angular ng-repeat and images in a row
- → Conditional BG Color on AngularJS
- → Should I 'use strict' for every single javascript function I write?
- → getting the correct record in Angular with a json feed and passed data
- → "Undefined is not a function" at .toBe fucntion
- → angularjs data binding issue
- → Angular / JavaScript auto hydrate an instance
- → Convert generic text string in json object into valid url using Angular