Lets say we have a database:
Recipes
recipe_key(some uniq key generated when data pushed)
ingredients:pepper
how do i retrieve pepper value with recipe_key ? I checked documentation of angularfire2 it says use snapshotchanges but with this code i can only get "Recipes".I guess i need to go 1 more layer down ?
constructor(afDb: AngularFireDatabase) {
afDb.object('/recipes/').snapshotChanges().map(action => {
const $key = action.payload.key;
const data = { $key, ...action.payload.val() };
return data;
}).subscribe(item => console.log(item.$key));
}
The documentation is correct, you should be using snapshot changes so that you can get the key property from the payload object.
Looking at your code I believe you forgot to add the key to the object()
method of the AngularFireDatabase
const recipeKey = '<your-push-key>';
afDb.object(`/recipes/${recipeKey}`).snapshotChanges().map(action => {
const $key = action.payload.key;
const data = { $key, ...action.payload.val() };
return data;
}).subscribe(item => console.log(item.$key));
If you want to retrieve a list with the $key property you can use this method.
afDb.list(`/recipes`).snapshotChanges().map(actions => {
return actions.map(action => {
const $key = action.payload.key;
const data = { $key, ...action.payload.val() };
return data;
});
}).subscribe(items => console.log(items));