2017-07-20 52 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

您可以创建打字稿类:

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); 
    } 
} 
相关问题