Reputation: 14155
I'm fetching data over web service and I want to populate my object User with address object.
When trying to assign value to object this.user.address.residentialAddress I'm getting
ERROR TypeError: Cannot set property 'residentialAddress' of undefined
Same error applies when trying to instantiate using constructor. Simple console.log(this.user.address.residentialAddress.City); outputs value.
My guess is that I don't create object properly but I cannot see the solution?
private user: MyUser;
...
this.user = new MyUser();
this.user.address.residentialAddress = {
City: data.address.residentialAddress.City,
StreetAddress: data.address.residentialAddress.StreetAddress,
Suburb: data.address.residentialAddress.Suburb,
Province: data.address.residentialAddress.Province
};
export class Address {
public StreetAddress: string;
public Suburb: string;
public City: string;
public Province: string;
constructor(street: string, suburb: string, city: string, province: string){
this.StreetAddress = street;
this.Suburb = suburb;
this.City = city;
this.Province = province;
}
}
export class MyUser {
address: {
residentialAddress: Address;
postalAddress: Address;
}
....
}
Upvotes: 0
Views: 44
Reputation: 5698
private user: MyUser;
...
this.user = new MyUser();
////////////////////////////////////////////////////
/////// Add this line `this.user.address = {}`
////////////////////////////////////////////////////
this.user.address = {}
this.user.address.residentialAddress = {
City: data.address.residentialAddress.City,
StreetAddress: data.address.residentialAddress.StreetAddress,
Suburb: data.address.residentialAddress.Suburb,
Province: data.address.residentialAddress.Province
};
export class Address {
public StreetAddress: string;
public Suburb: string;
public City: string;
public Province: string;
constructor(street: string, suburb: string, city: string, province: string){
this.StreetAddress = street;
this.Suburb = suburb;
this.City = city;
this.Province = province;
}
}
export class MyUser {
address: {
residentialAddress: Address;
postalAddress: Address;
}
....
}
Upvotes: 0
Reputation: 8423
I think you should put address in the constructor:
export class MyUser {
public address: object;
constructor(){
this.address = {
residentialAddress: Address;
postalAddress: Address;
}
}
}
This would make user.address
be defined after instantiation and the Cannot set property 'residentialAddress' of undefined
should be gone.
Upvotes: 1