Angular2 object cannot set property of undefined
17,330
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);
});
}
}
Related videos on Youtube
Author by
raulnoob
Updated on September 16, 2022Comments
-
raulnoob over 1 year
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.