简体   繁体   中英

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

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 -

[
 {
   "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' ) -

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. 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],
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM