【问题标题】:Setting an enum value into a json object in Angular在Angular中将枚举值设置为json对象
【发布时间】:2021-02-18 22:00:13
【问题描述】:

我有一个常数

const requestBody: RequestBody = {
  clientId: clientId,
  orderingId: 113875599,
  receivedSignatureFlag: 'N',
  saturdayDeliveryFlag: 'N',
  deliveryMethodOptionCode: 'USPS',
  orderItemsList: [
    {
      itemCode: 'A123'
      transferCode: 'MAIL',
      specialHandling: 'N',
      deliveryExternalFlag: 'Y',
      orderQuantityAmount: 1,

    }
  ]
};

我已经为字符串值创建了一个枚举,并希望从该枚举中设置值。 这是枚举

export enum ReqBodyEnum {
  RCVD_FLAG = 'N',
  SAT_DELIVERY_FLAG = 'N',
}

我试过设置

receivedSignatureFlag:ReqBodyEnum[ReqBodyEnum.RCVD_FLAG]  -> this isnt working.

也试过了

receivedSignatureFlag:ReqBodyEnum.RCVD_FLAG

从枚举中设置值的最佳方法是什么?

【问题讨论】:

    标签: json angular typescript enums


    【解决方案1】:

    您似乎误解了枚举是什么。将枚举视为给定属性的潜在值(常量)的集合。

    例如,在 TypeScript 中,这将表示为:

    enum VehicleType {
      motorcyle = 'motorcycle',
      car = 'car',
      truck = 'truck',
      van = 'van'
    }
    
    class Vehicle {
      ...
      type: VehicleType;
      ...
    }
    

    要使上述内容适合您的回复,您需要重新考虑该方法。理想情况下,您希望为每个需要它的属性创建一个枚举,并为请求正文创建一个类型。然后,您可能希望将该类型应用于控制器中的常量,并使用您创建的枚举将值分配给属性。这可能看起来像这样:

    // Potentially a class, but I've used an interface for this example
    interface RequestBody {
        clientId: number;
        orderingId: number;
        receivedSignatureFlag: ReceivedSignature; // Created a seperate enum for these 2 properties   
        saturdayDeliveryFlag: SaturdayDelivery;   
        deliveryMethodOptionCode: string;         // Could potentially also be an enum
        orderItemsList: any[];                    // Using a generic type here to save time
    }
    
    enum ReceivedSignature {
        N = 'N',
        Y = 'Y',
        DIGITAL = 'DIGITAL'
    }
    
    enum SaturdayDelivery {
        N = 'N',
        Y = 'Y',
    }
    
    // This is now typed
    const requestBody: RequestBody = {
        clientId: clientId,
        orderingId: 113875599,
        receivedSignatureFlag: ReceivedSignature.N,
        saturdayDeliveryFlag: SaturdayDelivery.N,
        deliveryMethodOptionCode: 'USPS',
        orderItemsList: [
            {
                itemCode: 'A123',
                transferCode: 'MAIL',
                specialHandling: 'N',
                deliveryExternalFlag: 'Y',
                orderQuantityAmount: 1,
            }
        ]
    };
    

    应该注意的是,如果标志本质上是二进制的(“N”或“Y”),您可能应该坚持使用原始布尔类型。请注意,我已将 DIGITAL 常量添加到 ReceivedSignature 枚举中,使该枚举成为该属性所必需的。然而,可以说saturdayDeliveryFlag 属性不需要枚举。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多