如何初始化包含子接口的接口

时间:2017-09-05 12:24:43

标签: angular typescript

子接口中的变量未定义。如何初始化接口的所有变量,包括子接口。

我尝试使用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'

1 个答案:

答案 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: {} };

    ...
}