Angular2 Mapping nested json array to model

后端 未结 1 735
夕颜
夕颜 2021-02-03 10:43

I am not able to map the nested json array which is response from Web to my model array in Angular2. Suppose I have json array response as below:

[{
    \"base_         


        
相关标签:
1条回答
  • 2021-02-03 11:18

    You can simplify your model and your mapping a lot. You don't need to map your API response manually. JavaScript/TypeScript can do this for you.

    First you need multiple interfaces.

    export interface DeiInstance { 
        base_url: string;
        date: string;
        lname: string;
        name: string;
        description: string;
        id: number;
        creationDate: string; //probably date
        version: string
        metrics: Metric[];
        key: string;
     }
    
     export interface Metric {
          val: decimal;
          frmt_val: decimal;
          key: string;
     }
    

    You can then use the as-"operator" of TypeScript to cast your API response to the DeiInstance Type.

     sealSearch(term: string): Observable<DeiInstance[]> {
          return this.http.get(this.sealUrl + term)
               .map(response => response.json() as DeiInstance[])
               .catch(this.handleError);
     }
    

    If you use interfaces instead of classes you have also the advantage that you have less production code which will be sended to the client browser. The interface is only there for pre-compile-time or however you want to call it.

    Hope my code works and it solves your problem.

    0 讨论(0)
提交回复
热议问题