2017-02-23 121 views
0

在我Angular2-應用I'm接收通過HTTP請求的JSON響應那種看起來像:地圖JSON響應到嵌套打字稿對象與rxjs

{ 
    "documents": [ 
    { 
     "title": "Example-Doc 1", 
     "versions": [ 
     { 
      "fileSize": 15360 
     }, 
     { 
      "fileSize": 2048 
     } 
     ] 
    }, 
    { 
     "title": "Example-Doc 2", 
     "versions": [ 
     { 
      "fileSize": 15360 
     }, 
     { 
      "fileSize": 2048 
     } 
     ] 
    } 
    ], 
    "meta": { 
    "total": [2] 
    } 
} 

現在我不知道如何映射這個結構到我的TypeScript類,我檢查了不同的方法,但它從來沒有工作。實際上我需要調用Version類的構造函數。

export class Document { 
    title: string;  // Titel des Dokuments 
    versions: Version[]; 
} 

回答

0

如果您要進行序列化和反序列化複雜的類需要,我建議你實現靜態方法,你的類像fromJsontoJson - 但是不知道你的類答案的其餘部分將是怎樣的一個猜工作:

假設你有一個適當的fromJson,那麼你可以像下面的地圖數據:

const myDocuments: Document[] = myJson.documents.map(Document.fromJson); 

而且fromJson - 方法可以看看李關鍵字:

class Document { 
    constructor(public title: string, public versions: Version[]) 

    public static fromJson(json: any): Document { 
     return new Document(
      json.title, 
      json.versions.map(Version.fromJson) 
     ); 
    } 
} 

class Version { 
    constructor(public fileSize: number) {} 

    public static fromJson(json: any): Version { 
     return new Version(json.fileSize); 
    } 
}