简体   繁体   English

Angular:如何将字符串映射到枚举

[英]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.

相关问题 Angular:将字符串数组映射到http get调用中的枚举值数组 - Angular: map string array to array of enum values in http get call 如何将我的字符串键映射到一些可能的枚举值? - How to map my string key to some possible enum values? JS:如何从字符串转换为枚举到 map 键? - JS: How to convert from string to enum to map key? 将字符串转换为角度为 8 的枚举值 - convert string to enum Value in angular 8 如何使用 angular 材料 select 与字符串 map - How to use angular material select with string map Angular,如何跟踪 Map<string, any> () 修改?</string,> - Angular, how to track Map <string, any>() modification? 如何在带有kendo ui的odata查询字符串中为角度FilterDescriptor生成枚举比较 - how to generate an enum comparison in an odata query string with a kendo ui for angular FilterDescriptor 如何编写一个 function,我可以在其中将枚举的键作为字符串传递并获取映射到它的值? 使用 angular 11 - How to write a function where I can pass the key of the enum as a string and get the value mapped to it? Using angular 11 如何将三元重构为具有属性的 Enum Map? - How to refactor ternary into Enum Map with properties? 如何将 map 枚举到 Storybook 中的 select 下拉列表? - How to map enum to select dropdown in Storybook?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM