Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a JSON response to component model in TypeScript.

I have an Angular 2 app that returns a JSON string. I want to take that JSON string and map its values to a model.

From my understanding, a TypeScript model file is supposed to help in mapping an HTTP Get response to an object - in my case a class classed 'CustomObject'. Here's my TypeScript model file which I created for TypeScript to recognize:

export class CustomObject {
    public Name: string;
}

Here's what my JSON string looks like (slightly modified from Chrome dev tools to eliminate unnecessary variables):

"{
   "EventType": 3,
   "Description": "Test Description",
   "LocationName": "DefaultLocation",
   "Name": "TestName"
}"

I want to take that JSON string and map the 'Name' value ("TestName" to an existing CustomObject's variable I have declared in my home.ts file which is null by default:

public activeCustomObject: CustomObject = null;

However, after executing the HTTP Get method to retrieve the JSON response (I expect variable 'activeCustomObject' to now its 'Name' field set to 'TestName', calling {{activeCustomObject.Name}} in my HTML file print nothing. I've done the proper imports and set the providers.

Here's how I'm subscribing:

this._customObjectService.getCustomObject()
    .subscribe(res => {
        this.activeCustomObject = res;
    });

and this is how I'm calling the GET method:

getActiveCustomObject() {
    return this._http.get('/test/customobject')
        .map((response) => {
            console.log(response);
            return response.json;
        });
}

Any ideas as to why calling {{activeCustomObject.Name}} print nothing in my HTML? Chrome dev tools show the JSON is returning a proper JSON string with the data I need (mainly name). I plan to use the other values in the JSON string so I can't just make the HTTP GET return the name field - I need to know why the returned JSON string isn't getting mapped to the Custom Object variable.

like image 445
Roka545 Avatar asked Nov 28 '25 14:11

Roka545


1 Answers

I think that it's because your data are loaded asynchronously. I guess that you have an error in your JavaScript console...

You could try to use the Elvis operator this way:

{{activeCustomObject?.Name}}

I see also another problem. You need to call the json method on the response not a property:

getActiveCustomObject() {
  return this._http.get('/test/customobject')
    .map((response) => {
        console.log(response);
        return response.json(); // <-----------
    });
}
like image 161
Thierry Templier Avatar answered Dec 01 '25 05:12

Thierry Templier