Cannot read property 'X' of undefined


#1

i’m running a local server with json-server where i get my mockup data from.
I want to load data in my app.html like this:

Welkom

{{user.firstname}}

I've added a provider and added it to my app.component.ts like i always do but this is the first time i load it my app.component. When i serve my app i get the following the runtime error: Cannot read property 'firstname' of undefined But if i put a console.log in my function i get the data: getUser(){ this.restProvider.getUser() .then(data =>{ this.user = data; console.log(this.user) }); } Is it even possible to load data in the app.html? because i do the exact same thing as i do with other pages and that works.

#2

user.firstname is called before user is defined. You can do any of the following:

{{ user ? user.firstname : null }}
<ng-container *ngIf="user">
    {{ user.firstname }}
</ng-container>
class AppComponent {
    public user = {};
}

I’d personally go with the ng-container


#3

Thank you so much!
Why is it beter to go with the ng-container? i’m new to this :stuck_out_tongue:


#4

Even better to populate the user objecr with empty data so u dont need to test

public user = {firstname:''};

Do this in the constructor or when declaring the variable in the class


#5

And angular allows this in template to dodge issues. Easier then the suggested elvis

{{user?.firstname}}


#6

Just personal preference, really. :slight_smile: It looks better than {{ user ? user.firstname : null }} and I’m not a fan of pre-populating a property unless necessary.

Latest suggestion from @Tommertom is probably the most ideal one!


#7

Indeed matter of opinion

I go for pre populating to keep code simple and demonstrate control of data


#8

So how does that work?
this goes in my class: user: any;
then in my constructor i have: this.getUser(); after this.initializeApp();
And this is my function:
getUser(){
this.restProvider.getUser()
.then(data =>{
this.user = data;
});
}
Where should i place the empty object?
*i switched accounts…

Thank you @mich356c and @Tommertom for your help!


#9

If that is the approach you wish to use:

user: any; -> user: any = {};

Though keep in mind, if you then use nested properties like {{ user.likes.cake }} in your template, it will throw the same error as before, since it’s trying to read cake of likes which is undefined.

You can nest the Elvis operator ({{ user?.likes?.cake }}), but then it just starts looking messy too :wink: