2017-07-20 31 views
-2

私はサービスから来ているjsonデータを持っていますが、現在私は模擬JSONデータを作成しています。 要件:このデータをクラスに追加したいとします。誰かがクラスのアーキテクチャーをどのようにするべきか、JSONからクラスにデータを取り込み/マップする方法を提案できますか?クラス/モデルにangular2のJSONデータを取り込む方法

JSONデータ

export const Data = 
{ 
    "elements": [ 
     { 
      "name": "stringVal", 
      "facets": [ 
       { 
        "name": "Cameras", 
        "link": { 
         "type": "Link", 
         "uri": 
        }, 
        "hits": { 
         "type": "Link", 
         "uri": 
        }, 
        "selected": true 
       }, 
       { 
        "name": "Cameras2", 
        "link": { 
         "type": "Link2", 
         "uri": 
        }, 
        "hits": { 
         "type": "Link2", 
         "uri": 
        }, 
        "selected": false 
       }, 

      ], 
      "displayType": "text_clear", 
      "selectionType": "taxonomic", 

     }, 
     { 
      "name": "Brand", 
      "facets": [ 
       { 
        "name": "Canon", 
        "link": { 
         "type": "Link", 
         "uri": 
        }, 
        "hits": { 
         "type": "Link", 
         "uri": 
        }, 
        "selected": false 
       }, 
       { 
        "name": "Canon", 
        "link": { 
         "type": "Link", 
         "uri": 
        }, 
        "hits": { 
         "type": "Link", 
         "uri": 
        }, 
        "selected": false 
       }, 
      ], 
      "displayType": "text_clear", 
      "selectionType": "single", 

     }, 
    ], 
    "type": "stringValue", 
    "name": "filters" 
} 
+0

あなたのサービスは、あなたがしようとしている何を、どこで、あなたのコードで問題がありますか? – Alex

+0

私はなぜあなたのクラスでそれをしたいのですが、これらの値をあなたのテンプレートに表示したいのですか? –

答えて

0

あなたはtypescriptですクラスを作成することができます

public class Data { 
 
    type: string; 
 
    name: string; 
 
    elements: ElementItem[]; 
 
} 
 

 
public class ElementItem { 
 
    name: string; 
 
    displayType: string; 
 
    selectionType: string; 
 
    facets: Facet[]; 
 
} 
 
public class Facet { 
 
    name: string; 
 
    selected: Boolean; 
 
    link: Link; 
 
    hits: Hit; 
 
} 
 
public class Link { 
 
    type: string; 
 
    uri: string; 
 
} 
 
public class Hit { 
 
    type: string; 
 
    uri: string; 
 
}

0

モデル

export class YourModel { 
    yourProperty: any; 
    yourProperty2: any; 

    constructor(options: { 
     yourProperty: any; 
     yourProperty2: any; 
    }) { 
     this.yourProperty = options.yourProperty; 
     this.yourProperty2 = options.yourProperty2; 
    } 
} 

を私たちは、要件を参照することができ

@Injectable() 
export class YourService { 
    getData() { 
     return this.http.get('path_to_your_json') 
     .map((response) => { 
      let result = []; 
      response.forEach(object => { 
       result.push(new YourModel(object)); 
      }); 
      return result; 
     }) 
    } 
} 
0
export class Person { 

    dateOfBirth: Date; 
    age: number; 
    comments: string[]; 

    constructor(values: Object = {}) { 
     Object.assign(this, values); 
    } 
} 
関連する問題