Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 object cannot set property of undefined

So I have this little app in Angular2, and I'm trying to define an object. This is the main component.

export class ContactComponent  {
    person: {
    firstname: string;
    lastname: string;
}
constructor(private PeopleService: PeopleService){
}

ngOnInit(){

this.PeopleService.fetchData().subscribe(
    data=> {
        this.person.firstname=data.results[0].name.first;
        console.log(this.person.firstname);
    });
  }
}

Then in the console log I get:

Cannot set property 'firstname' of undefined

I can't figure it out. Thanks.

like image 267
raulnoob Avatar asked Mar 21 '17 12:03

raulnoob


1 Answers

You are just defining the type of person here (the colon stands for type annotations eg:propertyName:Type) :

person: {
    firstname: string;
    lastname: string;
}

What you have done here is telling the compiler that person is an object literal with 2 string properties firstname and lastname. It defines what can be store in that property, not what it contains.

You should assign a value first, otherwise, it will be undefined

interface Person {
    firstname ? : string; // the "?" makes the property optional, 
    lastname ? : string; //  so you can start with an empty object
}
export class ContactComponent {

    person: Person = {}; // initializing with an empty object

    constructor(private PeopleService: PeopleService) {}

    ngOnInit() {

        this.PeopleService.fetchData().subscribe(
            data => {
                this.person.firstname = data.results[0].name.first;
                console.log(this.person.firstname);
            });
    }
}
like image 145
n00dl3 Avatar answered Oct 14 '22 06:10

n00dl3