I'm building an Angular2 app on Firebase using angularfire2.
Items returned from the realtime db have additional fields on them (e.g. $key, $exists) that can be useful in your application. But if you don't include those keys in your model definitions, typescript throws errors.
For example, say I have a class called item:
export class Item {
name: string,
price: number,
isOnSale: boolean
}
When that item is returned via angularfire2 it has additional firebase fields (e.g. $key, $exists, etc.), that I sometimes want to access:
constructor(private af: AngularFire){
this.af.database.list('items').subscribe(items => {
items.forEach(item => this.doSomethingWithDbItem(item));
})
}
doSomethingWithDbItemAndThenUpdate(item: Item){
// Now, if I want to access the $key field, I get a typescript error because
// $key does not exist on my class definition
if( item.name === 'toy_truck'){
const key = item.$key; // Will throw error typescript compile error
this.af.database.object(`items/${key}`).set({isOnSale: true})
}
}
Is there a best practice for handling this? I could add the db keys directly to the model. Or maybe create a FB class that has $key, $exists, etc. and then have my Item class and other classes extend FB?
This is a bit of a contrived example, so code may not be exactly right, but hopefully my point/question is clear.