我正在使用angularfire2在Firebase上构建一个Angular2应用程序。
从实时数据库返回的项目上具有其他字段(例如$key、$exists),这些字段在您的应用程序中很有用。但是,如果您没有在模型定义中包含这些键,则打字稿会引发错误。
例如,假设我有一个名为 item 的类:
export class Item {
name: string,
price: number,
isOnSale: boolean
}
当该项目通过 angularfire2 返回时,它有额外的火碱字段(例如$key、$exists等),我有时想访问这些字段:
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})
}
}
是否有处理此问题的最佳实践?我可以将数据库键直接添加到模型中。 或者创建一个具有$key、$exists等的 FB 类,然后让我的 Item 类和其他类扩展 FB?
这是一个有点人为的例子,所以代码可能不完全正确,但希望我的观点/问题很清楚。
此代码中的items
:
this.af.database.list('items').subscribe(items => {
items.forEach(item => this.doSomethingWithDbItem(item));
})
将是 Object
实例的数组。它不会是Item
实例的数组。也就是说,item instanceof Item
将是false
.
因此,告诉TypeScript这就是它们没有多大意义。
相反,您应该使用接口来描述模型的形状。如果你要使用接口,使用具有 AngularFire2 属性的基本接口是微不足道的:
export interface AngularFireObject {
$exists: () => boolean;
$key: string;
$value?: any;
}
export interface Item extends AngularFireObject {
name: string;
price: number;
isOnSale: boolean;
}