【问题标题】:Angular2 typescript map response to new typeAngular2打字稿映射对新类型的响应
【发布时间】:2017-09-28 03:38:53
【问题描述】:

拥有

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;
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    在订阅中使用这个,

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

    编辑

    根据cmets,修改,

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

    看看能不能解决。

    【讨论】:

    • 我知道一种类型与其他类型不兼容,老实说 IUserGroup 具有相同的 IUserDifferentGroup 但还有 2 个字段
    • 我明白了。请同时显示types,以查看区别
    • 如果您可以通过在其interface 定义中对这些属性使用猫王运算符? 来使IUserGroup 中存在的另外两个字段成为可选字段。
    • 首先,它们不一样。在接口中,属性名称和它的类型一样重要。我可以看到IdName 映射到IdGroupNameCode 类型为 string 在另一个界面中映射到什么? (其余属性有booleans)
    • 我只想将 Id 和 name 映射到 GroupName
    猜你喜欢
    • 2019-11-19
    • 2022-12-07
    • 2022-08-17
    • 2018-06-18
    • 2018-06-16
    • 2021-04-02
    • 2017-05-12
    • 2023-03-15
    • 2018-09-05
    相关资源
    最近更新 更多