Angular2打字稿映射响应新类型

时间:2017-09-27 19:12:25

标签: angular typescript

userGroups: IUserGroup[];
this.service.getUserGroups().subscribe(g => this.userGroups = g);

getUserGroups返回IUserDifferentGroup[],但IUserGroupIUserDifferentGroup都有相同的字段IUserGroup还有更多,如何将响应映射到新类型?

interface IUserDifferentGroup{
    Name: string;
    Code: string;
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

1 个答案:

答案 0 :(得分:3)

在订阅内使用

this.service.getUserGroups().subscribe(g => this.userGroups = g as IUserGroup[]);

修改

根据评论,修改,

interface IUserDifferentGroup {
    Name: string;
    Code?: string; // <-- made this optional
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

然后更改订阅,

this.service.getUserGroups().map((g) => return {Name: g.GroupName, Id: g.Id})
 .subscribe(g => {
  this.userGroups = g as IUserGroup[];
});

看看它是否修复了它。