子接口中的变量未定义。如何初始化接口的所有变量,包括子接口。
我尝试使用extends,但它仍然无效。
接口
export interface UserModel {
username?: any;
email?: any;
first_name?: any;
last_name?: any;
profile?: ProfileModel;
}
interface ProfileModel {
nome_empresa?: any;
cnpj?: any;
}
组件
export class PerfilComponent implements OnInit {
user = <UserModel>{};
constructor(private perfil: PerfilService) { }
ngOnInit() {
this.perfil.get().subscribe((perfil) => {
this.user = perfil;
})
}
在模板中
PerfilComponent.html:61 ERROR TypeError:无法读取未定义的属性'nome_empresa'
PerfilComponent.html:61 ERROR TypeError:无法读取未定义的属性'cnpj'
答案 0 :(得分:0)
我不清楚你在prefil
中得到了什么
你可以这样做:
this.perfil.get().subscribe((perfil) => {
this.user = Object.assign({}, { profile: {} }, perfil);
});
只是为了确保this.user.profile
不是undefined
。
您甚至在发出请求之前可能会收到该错误,因此它也应该是:
export class PerfilComponent implements OnInit {
user = <UserModel> { profile: {} };
...
}