I have an angular component that I will fillout based on an API call to a Nodejs server.
This API returns an object sort of like this:
{
"data": {
"firstname": "John",
"lastname": "Doe",
"age": 34
}
}
So I create at the TS:
public data: any={};
And then I call the API at ngOnInit, which populates data.
My problem is that at the HTML file, when I want to print lets say data.firstname:
Your name is {{data.firstname}}
Im getting this error:
TypeError: undefined is not an object (evaluating ctx.data.firstname)
I've learn that if I print the name as follows, that error won't show up:
Your name is {{data?.firstname}}
But it doesn't work in all cases.
Is there a way to fix this issue? The application works fine; I just dont like to see the errors on the console. Im planning to build this application the cleanest possible way.
thanks.
CodePudding user response:
By doing this public data: any={};
, you initialize your data
attribute as an object instance with no fields.
Thus, on component creation:
data
is never undefined (so thedata?.xxx
in the template is useless)- but
data
has nofirstname
field
That's why you get an error. To fix it declare your attribute as
public data?: any;
And as your data will be undefined, the {{ data?.firstname }}
in the template won't be resolved until the OnInit has correctly initialized your attribute with the right fields.
CodePudding user response:
You can try putting *ngIf="data" on the containing element.
<div *ngIf="data && data.firstname">
<p>Your name is {{data.firstname}} {{data.lastname}}</p>
<p>Your age is {{data.age}}</p>
</div>