3

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.

2
  • Did you resolve your question? Commented Jun 29, 2017 at 14:32
  • See accepted answer from Thierry Templier. Commented Jun 29, 2017 at 17:39

1 Answer 1

3

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(); // <-----------
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't even see than json method typo - that fixed it - thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.