【问题标题】:Angular Get value from string Enum using integerAngular使用整数从字符串枚举中获取值
【发布时间】:2022-07-15 19:28:18
【问题描述】:
export enum RoleTypesEnum {
    RoleA = 'Role is A',
    RoleB = 'Role is B',
}

// in TS file
public RoleTypesEnum = RoleTypesEnum;

我想使用整数从枚举中获取字符串值(例如 角色是 B)。

如果我输入 HTML 或 TS 文件 console.log(RoleTypesEnum[0]) 它打印 undefined.

因为我从后端接收整数(例如:JSON -> RoleTypes:0 或 1)。

我可以使用Object.values(RoleTypesEnum); 制作管道并获取枚举值,但我想知道最佳实践。管道解决方案:Angular Pipe extracts from Enum values, but generic for any Enum

后端-前端同步

数据库将枚举存储为整数。在后端(ASP.NET)中,DTO 和模型具有枚举类型的字段。当 Controller 返回时,它会自动从枚举中返回一个 JSON 格式的整数。

  1. 如果我从后端返回 string 值 (json: "roleB") 而不是整数 (json: 1)。在返回 JSON 之前,我需要从 Enum 转换为字符串。而且我觉得数据库和后端设计要搞砸了。
  2. 如果我从后端返回整数当前问题案例),我不能有自定义字符串值。因为我拥有的唯一数据是一个整数和 'RoleTypesEnum[1]' => undefined。 除非我用整数设置枚举
export enum RoleTypesEnum {
    RoleA = 0,
    RoleB = 1,
}

但是我不能有自定义字符串值(例如:“Role is B”)。

【问题讨论】:

  • 我发现你的做法很干净,这个问题很有趣。恕我直言,真正的问题是设计问题。后端不应该知道前端定义枚举值的顺序。最好将值交换为字符串。
  • 最佳实践是将此 Enum 类导入您的组件,然后是 console.log(this.RoleTypesEnum.RoleA)。看来您正在尝试将其记录为数组,这只是带有键值对的直接对象
  • @ArnaudDenoyelle 更新了关于您的观察“后端-前端同步性”的问题。
  • @GarrettWitzenburg 我只从后端获得整数。 this.RoleTypesEnum.RoleA 有效,但我不知道在 UI RoleA 或 RoleB 上显示哪个。我只知道整数。

标签: angular typescript enums type-conversion roles


【解决方案1】:

以这种方式管理自定义字符串:

Shared/enums-descriptions.ts

export const MyTypesEnumDescription: {
    [key in MyTypesEnum]: string;
} = {
    [MyTypesEnum.Standard]: 'Standard',
    [MyTypesEnum.Advanced]: 'Advanced Stage',
    [MyTypesEnum.Intermediate]: 'Intermediate Stage',
};

MyClass.ts

public selectBoxItemList = [
    new SelectListItem({
        value: MyTypesEnum.Advanced,
        text: MyTypesEnumDescription.InvalidCall,
    }),     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2013-07-18
    • 2020-07-11
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多