[英]proper way to create a typescript object
我一直在四處尋找,但沒有看到我正在尋找的答案。 如果我的問題重復,請告訴我。
我正在嘗試在打字稿中創建一個對象,其中包含自定義類型的屬性。
問題是我的服務器為對象提供了 url。 我不確定如何處理映射。 如果我沒有很好地解釋這一點,請原諒。 我對所有這些都很陌生。 順便說一句,我正在使用 Angular 和 Typescript
這是一個例子。 對象是這樣的:
export class Contact {
name : string;
address : {
street : string;
city : string;
}
}
但是,從我的服務器檢索到的 json 是這樣的:
{
"name" : "firstname lastname",
"address" : "http://localhost:5000/contacts/001"
}
如果我使用地址 url,我應該以 json 格式獲取地址。
謝謝你的時間!
解析您從服務器檢索到的 json,然后將其分配給您的屬性,如下所示
...
.subscribe(
data => {
this.name = data.name
this.address = data.adress
})
請注意,一個好的做法是定義一個單獨的服務來向服務器發出請求
如果我假設您的問題是關於如何將服務器檢索到的數據映射到本地打字稿對象,一種方法是在類中創建一個靜態方法以返回類的新實例,它需要一個“any”類型的對象並返回一個映射所有屬性后的對象。 在 http 請求返回后或訂閱后使用該方法,取決於您的設置。
export class Address {
constructor(public name:string, description: string){
}
public static NewInstance(address: any){
//map here
return new Address(address.db_name, address.address);
}
}
export class Student {
constructor(
public name : string,
public classes: StudentClass[],
public address: Address
){
}
public static NewInstance(student: any){
let studentclasses = student.classes.map(n => StudentClass.NewInstance(n));
return new Student(student.firstname+' ' + student.lastname, studentclasses, Address.NewInstance(student.addresss));
}
}
export class StudentClass {
constructor(public: name: string);
public static NewInstance(studentclass: any){
return new StudentClass(studentclass.namefromdb);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.