export enum RoleTypesEnum {
RoleA = 'Role is A',
RoleB = 'Role is B',
}
// in TS file
public RoleTypesEnum = RoleTypesEnum;
I want to get string value (ex Role is B) from enum using an integer.
If I type in HTML or TS file
console.log(RoleTypesEnum[0])
it prints undefined.
Because I receive integer from backend (ex: JSON -> RoleTypes: 0 or 1).
I can make a pipe and get enum values using Object.values(RoleTypesEnum);, but I am wondering for the best practice. The pipe solution: Angular Pipe extracts from Enum values, but generic for any Enum
Backend-Frontend synchronicity
The database stores the enum as integers. In backend (ASP.NET), DTO and models have field with enum type. When Controller returns, it automatically returns an integer in JSON from the enum.
- If from backend I return string value (json: "roleB") instead of integer (json: 1). I need a conversion from Enum to string before returning the JSON. And I feel like wrecking with the DB and backend design.
- If from backend I return integer (current question case), I can't have custom string values. Because the only data I have is an integer and 'RoleTypesEnum[1]' => undefined. Unless I set the enum with integers
export enum RoleTypesEnum {
RoleA = 0,
RoleB = 1,
}
But then I can't have custom string values (ex: "Role is B").