本文介绍了Angular2 TypeScript映射对新类型的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有

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

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

getUserGroups returns IUserDifferentGroup[] but both IUserGroup and IUserDifferentGroup have the same fields additionally IUserGroup have some more, how to map response to new type ?

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

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

推荐答案

在内部使用此订阅

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[];
});

查看它是否可以解决.

这篇关于Angular2 TypeScript映射对新类型的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:19