Reputation: 119
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.
Upvotes: 10
Views: 17919
Reputation: 31
Firstly create an object in the component class. ex:
employee=new Employee();
Then refer to this employee
object
Upvotes: 0
Reputation: 21564
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);
});
}
}
Upvotes: 15
Reputation: 457
First declare an object of person type on onInit()
.
person p=new person();
Upvotes: 0
Reputation: 478
Create a class and inherit in component. For Example see the below code
export class Person{
firstname: string;
lastname: string;
}
export class ContactComponent {
person=Person[];
constructor(private PeopleService: PeopleService){
}
ngOnInit(){
this.PeopleService.fetchData().subscribe(
data=> {
this.person.firstname=data.results[0].name.first;
console.log(this.person.firstname);
});
}
}
Upvotes: 0