What is the process for converting a template literal into JSON in Angular?

I am facing an issue with the code in my ty file:

onSubmit(form: NgForm){
console.log('Executed')
let data = `
  name: ${form.value.name},
  email: ${form.value.email},
  specialty: ${form.value.specialty},
  password:${form.value.password}

  `;
  this.http.post(`${ this.apiURL }/auth/register_lawyer`, data)
        .subscribe(
          result => {
            console.log(result)
          },
          error => {
            if(error.status == 400) {
              console.log(error);
            }
          }
        )
}

I am looking for a way to convert the received data from the form into JSON format. For example:

   data ={
"name":"Andrew",
"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e89c8d9b9c8da880879c85898184c68b8785">[email protected]</a>",
"specialty":"developer,
"password":"1234"

}

I need to send the data in JSON format via Post to my API, but I haven't found a solution yet. I attempted using JSON.stringify, however it did not work.

Answer №1

Your dados string is not considered valid JSON due to non-compliance with formatting rules (e.g. missing double-quotes for keys, lack of string delimiters, etc). It's advisable to avoid using template strings when creating JSON data as it may require handling tasks like escaping strings.

To address this issue, refactor your code to first construct a DTO object, and then you can create the dados template string separately if needed. One approach to prevent redundancy is to utilize a function that constructs the string by iterating through the properties of the DTO.

const dto = {
    name     : form.value.name,
    email    : form.value.email,
    specialty: form.value.specialty,
    password : form.value.password
};

const url = `${ this.apiURL }/auth/register_lawyer`;
this.http.post( url, dto )    
    .subscribe( resultado => {
        console.log(resultado)
        },
        erro => {
            if(erro.status == 400) {
                console.log(erro);
            }
        }
    );

const dados = `
    name: ${dto.name},
    email: ${dto.email},
    specialty: ${dto.specialty},
    password:${dto.password}
`;

If there is a need to generate multiple similar non-JSON dados strings (possibly for logging purposes), you can utilize the following method:

function createTextThatIsNotJson( obj ) {

    let text = "";
    for( const key in obj ) {
        if( text.length > 0 ) text += ",\r\n";
        text += "    " + key + ": " + obj[key];
    }
    return text;
}

const dados = createTextThatIsNotJson( dto );

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

Show validation message using Bootstrap near the submit button

My form consists of around 40 questions, some required and some optional. Upon clicking "submit," I utilize Bootstrap's form-validation.js to verify the form before submission, which works seamlessly. However, due to the length of the form, when a us ...

Techniques for removing a label value using JavaScript

There is a label named "test" being generated from the .cs [C# code] with the text "data saved successfully". However, when I click the save button, I want to clear its text. Currently, I have 3 required field validators with messages [cannot be blank, can ...

"Leveraging the Angular2 core module for efficient sharing in lazy loading

With 4 feature modules set to load lazily, there are multiple popup components needed for these modules. To handle this, a shared module has been created to export the components, with each feature module importing this shared module. However, one downside ...

What is the process of using 'DefaultImports' to import DTOs into TypeScript through ServiceStack?

Whenever I attempt to utilize the command line tools that come with ServiceStack for TypeScript, I continuously encounter issues with the DefaultImports functionality not behaving as anticipated or being particularly beneficial. What is the proper way to m ...

React Link updates the browser's URL without refreshing the page, yet fails to display any new content

Currently, I am working on developing a chat application where I am facing an issue with matching the id parameters to display each one upon clicking. The core components I am dealing with include Chatroom.js and RoomList, which acts as the navigation menu ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

Problem with the fixed header on a container causing a horizontal scroll bar

This scenario presents a bit of a challenge! I could solve it by adjusting the container's height, but that would disrupt the fixed position of the sticky header. My goal is to have a scrollbar visible in both the X and Y directions on the .scrollabl ...

Is there a way to easily toggle a Material Checkbox in Angular with just one click?

Issue with Checkbox Functionality: In a Material Dialog Component, I have implemented several Material Checkboxes to serve as column filters for a table: <h1 mat-dialog-title>Filter</h1> <div mat-dialog-content> <ng-container *ng ...

Can a TypeScript function be structured to return never (or throw) if a generic type extends a subtype without requiring casting?

(This code snippet is purely for demonstration purposes, as no real use-case exists here) I am attempting to create a function that throws an error if the input string is equal to "fish". I have achieved this using the as keyword, but I am curious if ther ...

C# POST data retrieval does not provide the anticipated outcomes

My goal is to set up a basic POST method for sending data to a form before processing the C# in the code-behind. The desired outcome is a plain-text string with some simple values: function postTasks() { var postdata = $("#taskReturnDiv").text(); try ...

Change the appearance of a bootstrap dropdown menu button when clicked on, whether it's the button itself or anywhere on the

Looking at this bootstrap dropdown example, I am trying to change the button's background color to blue only when the dropdown menu is expanded. Although I managed to achieve this by adding a click listener to the button, a problem arises when the use ...

The NextJS API is now pointing to the index.js file rather than the [id].js file

I am currently setting up an API in NextJS. In my /classes folder, I have index.js and [id].js files. The purpose of /classes/ is to retrieve all classes from the database or add a new class. The purpose of /classes/[id] is to fetch a specific class, upda ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...

Locating numerous words within a given string

In my quest to identify specific words within a comma-separated log, I have encountered an issue. The current code snippet effectively locates individual words, but struggles to find all three words together in the log. $log = "Left Side Turn, Left Side ...

The jQuery .animate function seems to be malfunctioning

I recently came across this jsfiddle link: http://jsfiddle.net/2mRMr/3/ However, the code provided is not functioning as expected: setInterval(function () { box.animate({ left: function (i, v) { return newv(v, 37, 39); }, ...

Whenever I anticipate receiving an array, Fetch always delivers a promise

I'm currently facing an issue with my simple API GET request. The array I need is always inside a promise and I can't figure out how to extract it or access the values stored within it. function getLocation(name) { let output = fetch(`http:// ...

Ways to trigger child components function from parent component

I am working with a parent-child component setup. In the child component (child.component.ts), there is a method called "childFunction()". Now, I need to call this method from within a function in the parent component. Can you guide me on how to achieve ...

What is the best way to retrieve the data-id from a button that has been appended?

JavaScript $("#btn").on('click', function(){ $("#result").append("<button type='button' id='btnid' data-id='show' //want to retrieve this class='close pull-right' aria-hidden='true&apos ...

The utilization of React Suspense results in the router props becoming null

When employing Suspense in my code, I have the following setup: <Route path="/courses" render={() => ( <Suspense fallback={HomePage}> <Courses /> </Suspense> ...

display angular filter for mat radio option selected from mat-radio group

On the screenshot provided below, there are 2 buttons within a mat radio group. The condition is that if modelForm.get('schedule').value equals '1', then only display the radio button with the value 'A'. Otherwise, show all va ...