[英]Angular2 convert response JSON to Typescript enum
In Angular2 I receive data from the server as a JSON object. 在Angular2中,我从服务器接收数据作为JSON对象。 One of the fields is a resource type. 其中一个字段是资源类型。 Which can be an image, video or audio. 可以是图像,视频或音频。 The enum looks like: 枚举看起来像:
export enum MediaType {
image,
video,
audio
}
However when I try to cast the response to an MediaType enum: 但是,当我尝试将响应转换为MediaType枚举时:
this.type = MediaType[data["type"]];
I got an error: 我收到一个错误:
error TS2322: Type 'string' is not assignable to type 'MediaType'.
Any thoughts? 有什么想法吗?
Is data['type'] part of the JSON response, containing a MediaType? 数据['type']是JSON响应的一部分,包含MediaType吗? If so it can be cast like this: 如果是这样,它可以像这样投射:
this.type = <MediaType> data["type"];
Your data["type"] should be number, either 0, 1 or 2... 您的数据[“类型”]应该是数字,0,1或2 ...
Consider this: 考虑一下:
enum MediaType {
image,
video,
audio
}
let type: MediaType;
type = MediaType[0] // image
type = MediaType[1] // video
type = MediaType[2] // audio
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.