我从 RESTful 服务获得以下数据:
[
{
"id": 42,
"type": 0,
"name": "Piety was here",
"description": "Bacon is tasty, tofu not, ain't nobody like me, cause i'm hot...",
}...
我正在映射这个类:
export enum Type {
Info,
Warning,
Error,
Fatal,
}
export class Message{
public id: number;
public type: Type:
public name: string;
public description: string;
}
但是当我在 Angular2 中访问“type”时,我只得到一个 int 值。但我想得到一个字符串值。
例如:
'message.type=0'
{{message.type}} => should be Info
'message.type=1'
{{message.type}} => should be Warning
最佳答案
TypeScript 中的枚举是运行时的数字,因此 message.type
将为 0
、1
、2
或 3
。
要获取字符串值,您需要将该数字作为索引传递到枚举中:
Type[0] // "Info"
因此,在您的示例中,您需要这样做:
Type[message.type] // "Info" when message.type is 0
关于javascript - 将 int 转换为 Typescript 中的枚举字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42299257/