我正在通过Web服务获取数据,我想用地址对象填充我的对象User。
尝试为对象this.user.address.residentialAddress分配值时,我正在
错误类型错误:无法设置未定义的属性“residentialAddress”
尝试使用构造函数进行实例化时会应用相同的错误。 简单的console.log(this.user.address.residentialAddress.City);输出值。
我的猜测是我没有正确创建对象,但我看不到解决方案?
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;
}
....
}
答案 0 :(得分:1)
我认为你应该在构造函数中添加地址:
ant clean all
这样可以在实例化后定义ant modulegen
并且export class MyUser {
public address: object;
constructor(){
this.address = {
residentialAddress: Address;
postalAddress: Address;
}
}
}
应该消失。
答案 1 :(得分:0)
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;
}
....
}