Glenn Utter Glenn Utter - 5 months ago 41
JSON Question

Angular 2: Access object data

In my Angular RC2 app I make an observable HTTP call that returns the following JSON to me from the API:

{
"success":true,
"data":
{
"Type": 1
"Details":{
"Id":"123",
"Name":"test",
"Description":"test"
}
}
}


I map the data like this:

this._myService.get(id)
.subscribe(
(data) => {
this.details = data.Details;
this.type = data.Type;
},
(error) => {
this.setError(error);
}
);


How do I access the values inside the "Details" object from here?

I tried:

{{details.Name}}


But that won't work and I can't use ngFor to loop it either.

Answer

You could use the Elvis operator for this:

{{details?.Name}}

As a matter of fact, you load your data asynchronously so details is undefined at the beginning.

Comments