How to assign an enum value to a JSON object in an Angular application

I am currently dealing with a scenario where I have a constant requestBody object being defined. It contains various properties like clientId, orderingId, receivedSignatureFlag, saturdayDeliveryFlag, and so on.

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

    }
  ]
};

To make the code more structured and maintainable, I decided to create an enum called ReqBodyEnum to hold all the string values that are used in the requestBody object.

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

Now, here comes the issue. When trying to set the receivedSignatureFlag property to the value from the enum, it doesn't seem to work as expected.

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

I also attempted another approach:

receivedSignatureFlag:ReqBodyEnum.RCVD_FLAG

However, none of these methods provided the desired outcome. So, I'm looking for suggestions on how to correctly set the value from an enum in this context. Any ideas or best practices would be greatly appreciated!

Answer №1

It appears that there may be a misinterpretation of what an enum represents. An enum can be thought of as a set of predefined values (constants) for a specific attribute.

For instance, in TypeScript, you could define an enum like this:

enum VehicleType {
  motorcyle = 'motorcycle',
  car = 'car',
  truck = 'truck',
  van = 'van'
}

class Vehicle {
  ...
  type: VehicleType;
  ...
}

To adapt this concept to your scenario, consider creating enums for each relevant attribute and defining a type for the request body. Then, apply this type to the constant in your controller and use the corresponding enums to assign values to the attributes. Here's an example:

// Potentially a class, but I've used an interface for this example
interface RequestBody {
    clientId: number;
    orderingId: number;
    receivedSignatureFlag: ReceivedSignature; // Separate enum created for these properties   
    saturdayDeliveryFlag: SaturdayDelivery;   
    deliveryMethodOptionCode: string;         // Could potentially also be an enum
    orderItemsList: any[];                    // Using a generic type here for simplicity
}

enum ReceivedSignature {
    N = 'N',
    Y = 'Y',
    DIGITAL = 'DIGITAL'
}

enum SaturdayDelivery {
    N = 'N',
    Y = 'Y',
}

// Type definition for requestBody
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,
        }
    ]
};

If the flags only have binary values ('N' or 'Y'), it might be more suitable to use primitive boolean types instead. Additionally, note the inclusion of the DIGITAL constant in the ReceivedSignature enum, which is necessary for that particular property. However, the necessity of the enum for the saturdayDeliveryFlag property could be debated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

javascript: Retrieve specific row data from Bootstrap Modal table and pass it back to the main webpage

I am a beginner in using bootstrap modals and JavaScript, and I need assistance in resolving the following issue. Desired Outcome: 1. When the parent screen opens the modal window, it should display a form to find a username: <div class="form-gro ...

Create attributes that share the identical name as certain properties of the parent class

Upon extending a module, I have encountered an issue related to declaring private properties. Specifically, when I attempt to declare a method like init() as private, an error message is generated: Types have separate declarations of a private property ...

The error message "customValueFormatter is undefined in ag grid for Angular" indicates that the custom

I have a separate JSON file with column definitions and I am attempting to add a value formatter to one of the fields. I am defining the value formatter function in the component file, but I am encountering an error stating "Exception = ReferenceError: cus ...

Angular 2 Dropdown Multiselect Plugin - Fully Customize Width to 100%

Currently working on integrating the angular-2-dropdown-multiselect component: https://www.npmjs.com/package/angular-2-dropdown-multiselect The component functions correctly, but I am looking to adjust its width to fit the container... I believe simply ...

Measuring the height of an element within its parent component using Angular 4

Check out my demo here I've created a basic parent component along with a child component. Is there a way to retrieve the height of the parent div from within the child component? import { Component, Input, ElementRef, OnInit, ViewChild } from &apo ...

InvalidTypeException: The properties accessed are undefined

Working with Angular 12 and encountering an error when trying to invoke a method within another method. Here is a simplified representation of my situation (in TypeScript, specifically for Angular: export class SomeClass { testvariable on ...

Share the Angular library distribution folder on a new git repository

I am faced with a dilemma regarding my Angular library that I often use in another project. The way I build my library is by running the command: ng build Upon executing this command, a dist/my-library directory is created at the library root. My goal is ...

Update the mat-chip-remove positioning attributes

While browsing through the mat-chip documentation, I came across the following information: MatChipRemove Provides proper (click) support and styling for using the Material Design "cancel" icon, which can be found at https://material.io/icons/#ic_cancel. ...

Angular version 10 does not allow for intentionally causing errors using the HttpClient delete() method

Currently, I'm working through an Angular tutorial and facing a challenge in the error-handling section. Despite my efforts to trigger an error with incorrect data in a HttpClient.delete()-request, I am unable to force one. To provide some context, I ...

Issues with string encoding after using NSUTF8StringEncoding

When attempting to download a JSON string from a server, I noticed that the formatting is not as expected. Apologies for the confusion, I am new to using Stack Overflow. Upon comparing the received string with the var_dump output from PHP, I observed that ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

Retrieve an item from an array using a Select component

Is there a way to retrieve the complete object representation of an item from a list in React? Currently, when I select an item and call handleChangeSelectAuto, the original value from useState is returned instead of the entire object. How can I ensure tha ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

What sets apart `this.user.id` from `this.user = {id: ....}`?

I am puzzled by the error thrown in the code below: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', templateUrl: './user.compone ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Error: The global variable "Stripe" has not been defined

Having trouble with integrating the Stripe API. Development Environment: "devDependencies": { "@angular-devkit/build-angular": "~0.803.20", "@angular/cli": "~8.3.23", "@angular/compiler": "~8.2.14", "@angular/compiler-cli": "~8.2.14", ...

`I'm experiencing difficulty sending JSON data to Typeahead using PHP`

I am having trouble passing an array of data from PHP to typeahead. I have tried various solutions but nothing seems to work. When I display the response on the console, it shows the array of strings but they are not populating in the typeahead field. PHP ...

Listening for a long press in Angular 2: A step-by-step guide

Check out this link for an AngularJS example. Curious how this functionality translates to Angular 2? ...

Expanding the List View with JSON data

Is there a way to implement an ExpandableListView that retrieves data from a server response in JSON array format for both its groups and children? I have used SimpleCursorTreeAdapter before, but it only works with cursors. I'm looking for an equiva ...

Presenting JSON data in a table format on-the-fly even without prior knowledge of the data's structure or field names

When working with my application, I will be receiving data in JSON format and I am looking to showcase this data in a tabular form within a web browser. It's important to mention that I won't know beforehand the structure or field names of the re ...