javascript - Mapping a JSON response to component model in TypeScript. -
i have angular 2 app returns json string. want take json string , map values model.
from understanding, typescript model file supposed in mapping http response object - in case class classed 'customobject'. here's typescript model file created typescript recognize:
export class customobject { public name: string; }
here's json string looks (slightly modified chrome dev tools eliminate unnecessary variables):
"{ "eventtype": 3, "description": "test description", "locationname": "defaultlocation", "name": "testname" }"
i want take json string , map 'name' value ("testname" existing customobject's variable have declared in home.ts file null default:
public activecustomobject: customobject = null;
however, after executing http method retrieve json response (i expect variable 'activecustomobject' 'name' field set 'testname', calling {{activecustomobject.name}} in html file print nothing. i've done proper imports , set providers.
here's how i'm subscribing:
this._customobjectservice.getcustomobject() .subscribe(res => { this.activecustomobject = res; });
and how i'm calling method:
getactivecustomobject() { return this._http.get('/test/customobject') .map((response) => { console.log(response); return response.json; }); }
any ideas why calling {{activecustomobject.name}} print nothing in html? chrome dev tools show json returning proper json string data need (mainly name). plan use other values in json string can't make http return name field - need know why returned json string isn't getting mapped custom object variable.
i think it's because data loaded asynchronously. guess have error in javascript console...
you try use elvis operator way:
{{activecustomobject?.name}}
i see problem. need call json
method on response not property:
getactivecustomobject() { return this._http.get('/test/customobject') .map((response) => { console.log(response); return response.json(); // <----------- }); }