[英]Angular: How to map string to enum
I am trying to map list of JSON to my model but one of my model property is enum but from the JSON I am getting that property as a sting so, how can map that string as a enum我正在尝试将 JSON 列表映射到我的模型,但我的模型属性之一是枚举,但是从 JSON 中我将该属性作为一个字符串,所以如何将该字符串映射为枚举
My enum -我的枚举 -
export enum Status {
HIGH = "High",
MEDIUM = "Medium",
LOW = "Low"
}
My model -我的模特——
import { Status } from "../enums/status.enum";
export class OrderModel {
id: number;
notification: string;
action: string;
status: Status ;
}
My json -我的 json -
[
{
"id": 1,
"notification": "Order has ben packed",
"action": "Assign to delivery",
"status": "High"
}
]
Here I am trying to map the JSON to my model but getting the error ( Type 'string' is not assignable to type 'Status' ) -在这里,我试图将 JSON 映射到我的模型,但出现错误(类型 'string' 不可分配给类型 'Status' ) -
import { OrderModel } from '../../models/order.model';
import orderData from '../json/order.json';
@Injectable({
providedIn: 'root'
})
export class OrderService{
//Here mapping JSON data to my model
orderModel: OrderModel[] = orderData;
constructor() {}
getOrderStatus() {
console.log(orderModel)
}
}
You'll need to mutate your incoming model to get the enum key.你需要改变你的传入模型来获取枚举键。 Interesting thing about TypeScript enums is that they are reverse-mappable.
TypeScript 枚举的有趣之处在于它们是可反向映射的。 Therefore if you map your incoming data to your actual class you can use the value to look up the enum key.
因此,如果您将传入的数据映射到您的实际类,您可以使用该值来查找枚举键。
orderModel: OrderModel[] = orderData.map(e => ({
...e,
status: Status[e.status],
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.