[英]Angular 2+: How to instantiate a class with data from backend?
我有一個Customer類和一個ICustomer接口。
interface ICustomer { <-- retrieved from backend
id: number;
name: string;
address: string;
// many more members
}
class Customer { <-- used throughout Angular app
// other fields
constructor(public data: ICustomer) {};
// other methods
refresh() {
// ... retrieve customer data from backend
}
}
我想使用{'id':5}之類的對象實例化Customer並調用其'refresh()'方法。 但是我遇到了編譯時錯誤,因為{'id':5}沒有實現ICustomer。
為了解決這個問題,我可以在每個成員之后用'?'修改ICustomer:
interface ICustomer {
id: number;
name?: string;
address?: string;
// many more members
}
現在{'id':5}(在技術上)是ICustomer的實例。
但這感覺不對。 有更好的解決方案嗎?
編輯:我可以將來自后端的數據保存在ICustomer類型的“數據”字段中。 我的問題是關於Customer類的實例化。
嘗試將{'id': 5} as ICustomer
應該管用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.