How to map JSON response to Model in Angular 4

user2480218 picture user2480218 · Jan 16, 2018 · Viewed 17.4k times · Source

I have tried a lot but I am not able to get endpoint response mapped to my model. I am using HttpClient and Angular4. I got data back from service but it is not mapped correctly to my model class.

I have following JSON which service is Returning:

{
    "result": [
        {
            "id": "1",
            "type": "User",
            "contactinfo": {
                "zipcode": 1111,
                "name": "username"
            }
        }
    ]
}

I have created a model in typescript which I will like to map to json response:

export interface result {
            zipcode: number;
            name: string;
}

This is how i call JSON endpoint.

result : string[] = [];

constructor(private http: HttpClient) {    }

public getList(): result[] {
        this.http.get<result[]>('url...', { headers: this.headers }).subscribe(

            data => {
             // 1. Data is returned - Working
                console.log('data: ' + data); 
                this.result= data;

                // This is the problem. My data is not mapped to my model. If I do following a null is returned
                console.log('data mapped: ' + this.result[0].name);
            },
            (err: HttpErrorResponse) => {
    // log error
            }
        );

        return this.result;
    }

Answer

Sajeetharan picture Sajeetharan · Jan 16, 2018

You need to import the interface in your component,

import { result } from '.result';

Your interface should look like,

interface RootObject {
  result: Result[];
}

interface Result {
  id: string;
  type: string;
  contactinfo: Contactinfo;
}

interface Contactinfo {
  zipcode: number;
  name: string;
}

and change the type of result as,

result : result;

and assign the result as,

this.result = data;

You can use http://www.jsontots.com/ to create the interface based on JSON