What is the best way to convert Angular form data into a POST request that the server can process?

In search of a solution to properly send data to the server in a format that it can accept. Currently, the title and descriptions are being successfully transmitted but the ratings are not coming through. It should be noted that there will be more than two types of ratings involved.

Here is an example of the POST request body format required by the server:

{
    "title": "Test title",
    "description": "Test description",
    "ratings": [
        {
            "value": 2,
            "category": {
                "name": "difficulty"
            }
        },
        {
            "value": 5,
            "category": {
                "name": "story"
            }
        }
    ]
}

The Angular component.ts file for the review form utilizes the FormBuilder. Users input scores ranging from 1-10 for different categories.

ngOnInit() {
  this.reviewForm = this.fb.group({
    gameTitle: ['', []],
    gameDescription: ['', []],

    scores: this.fb.group({
      difficulty: [, []],
      story: [, []]
    })
  })
}

Upon submitting the form in the Angular component.ts file, the data is sent to the server using a service. However, there are concerns about the structure of the ratings data and how to extract the score values and names for the ratings object.

onSubmit() {
  this.gameService.postReview(this.reviewForm.value)
    .subscribe(() => {
      this.success = true;
    });
}

Within the Angular API service.ts file, the postReview function handles the process of posting data to the server. How can the ratings data be formatted correctly for the server to accept it? And how can the score values and names be extracted for inclusion in the ratings object?

postReview(reviewData: any) {

  const gameReview = {

    title: reviewData.gameTitle,
    description: reviewData.gameDescription,

    ratings: [{
      value: reviewData.scores.value,
      category: {
        name: reviewData.scores.key
      }
    }]
  };

  return this.http.post(this.API_URL, gameReview, httpOptions);
}

Answer №1

It seems like there is something off with your HTTP post request. Headers are missing, which are crucial for a successful HTTP post. Your request should look more like this:


    var headers = new HttpHeaders({"Content-Type": "application/json" });
    this.http.post<LogAnswer>(url,
        {
            gameReview //your JSON object
        },
        {
            headers  //include any necessary headers here
        }
    ).subscribe(
        (val) => {
            //handle response data here
            console.log("Request was successful")
        },
        (error) => {
            console.log("Request failed");

        }
    );

I also suggest using Postman to test your API and see if the required headers need to be sent as well. Let me know if this helps!

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

Tips for viewing the console log in PhpStorm while executing an Angular application

I'm using Angular in a PhpStorm IDE. My code is full of "console.log" calls, and I've declared it as declare var console: Console; which is defined in an interface called Console from the lib.dom.d.ts library. But where can I see these log mess ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...

Uncovering the data from an Angular4 Observable

I'm attempting to retrieve a value from an HTTP call using http.get() and assign it to a local variable. Below is the code from my file UserName.ts import { Http } from '@angular/http'; this.http.get('http://localhost:8000/user/&apos ...

Effortlessly transfer model data to a different component in Angular upon clicking a button

Component A displays a list of Products, each with an option to view the details. When this option is clicked, I want Component B to show a list of items associated with that specific Product. I am having trouble passing the selected Product from Componen ...

Tips for RETRIEVING a particular cookie value in Angular version 14

"I've integrated the ngx-cookie-service library in my Angular project, but I'm experiencing an issue where two different cookies are being retrieved upon login even though the session id is already set in the backend. How can I ensure that m ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

Reset combobox to its default value when a different event happens

In my Angular 6 application, I have a reusable/shared component for a dropdown as shown below: <shared-dropdown-list-payments [valuesArray]="cashAccountLoaded" [defaultString]="defaultFromString" (outputEvent)="fromAccount($event)" tosca-id=" ...

Collaborative React front end elements are now housed in their own TypeScript project within Visual Studio 2017

In Visual Studio, our project structure includes the following: PublicClient, Admin, and SharedComponents. The SharedComponents project is essential because many components are shared between our client and admin interface. This structure is based on the f ...

What is the best way to combine two objects in Angular?

How can I merge objects in Angular 2? Object Response 1 0:Object 1:Object 2:Object 3:Object Object Response 2 0:Object 1:Object 2:Object 3:Object MyComponent Component resultdata :any=Array; fooddrinks_data_func(Defaultparams){ return this.Ci ...

Two distinct approaches for user interface and application programming interface

Here's a non-technical question that's been on my mind lately. I've noticed that developers often create separate projects for their Angular applications using Visual Studio Code, and separate projects for their .NET Core Web API applicatio ...

Could a tslint rule be implemented in Typescript classes to ensure method return types are enforced?

After diving into the tslint rules here, it seems that although the typedef rule's call-signature option might be close to what I need, it doesn't address the absence of a return type. Is there a specific rule (if one exists) that can enforce re ...

Having issues resolving 'fs' or 'path' in Edge-js and Angular projects

I'm currently working on an Electron Angular application that utilizes electron-edge-js to seamlessly transition between Angular and C# code without the need for a separate server. Everything seems to be running smoothly until I actually try to call e ...

Enhancing Vue.js form submissions with AJAX using Vuetify and vee-validate

Is there a way to handle JSON submission after form validation? Here's the code snippet: Contact.vue <template> <v-container grid-list-md fluid id="contact"> <v-container grid-list-md> <v-layout row wrap> ...

Experimenting with an rxjs service to perform a GET request within the component

When calling the service function, the syntax is as follows: get getLayerToEdit(): BehaviorSubject<VectorLayer> { return this.layerToEdit; } This function is then invoked in the ngOnInit method like this: ngOnInit() { this.annoServic ...

The speed of Mean Stack API calls leaves much to be desired

Our team has developed a MEAN stack application that functions smoothly on the client side. However, we have been facing issues with slow API requests and responses on the server side. For example, when a request is sent from Angular, it takes an average ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

What is the most efficient way to retrieve and update a Stencil component parameter without triggering a rerender of the component?

Within my Stencil component, there exists a not-Prop member variable known as private _zIndex. The value of this variable can be adjusted via a method call like Method() setZIndex( zIndex : number );, or it may change internally during the component's ...

Tips for how to retrieve an instance of a class or an error in Typescript

Currently, I am experimenting with TypeScript and a library called TypeORM while constructing custom repositories for my models. Within my models, specifically the Buyer model, there is a corresponding BuyerRepository featuring a method named createAndSav ...

What is the best way to implement rest parameters in Typescript when making a function call?

I have been working on NestJS and I am facing an issue with retrieving data from the database based on the name property that I pass in a service method. When I pass {"name": "item1"} in Postman, I get data related to item1. However, when I pass {"name":"i ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...