Issues encountered when using AngularJS2's post method to send data to an ASP.NET Core backend result

I recently delved into learning Angular2 and Asp.net core, but I encountered an issue when trying to post an object. Here is the relevant code snippet:

Service.ts file:

export class SubCategoryService {
//private headers: Headers;
constructor(private http: Http) {
    //this.headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
   // this.headers.append('Content-Type', 'application/json');
   // this.headers.append('Accept', 'application/json');
}
public createItem = (subCategory: SubCategory): Observable<SubCategory> =>
{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let toAdd = JSON.stringify(subCategory);
    return this.http.post("api/subcategory", toAdd, { headers: headers }).map((response: Response) => <SubCategory>response.json()).catch(this.handleError);        

}
}

Component.ts file:

export class SubCategoryComponent {
constructor(private service: SubCategoryService) { }
subCategories: SubCategory[];
SubCategory: SubCategory = new SubCategory();
onPost() {
    this.service.createItem(this.SubCategory).subscribe(
        subCategory => this.subCategories.push(subCategory),
        error => console.log(error),
        () => console.log('Get all items completed'));
    this.isLoading = true;

}
}

When it comes to the Asp.Net Core Controller:

[HttpPost]
    public async Task<JsonResult> Post(SubCategory subCategory)
    {
        return new JsonResult("");
    }

The controller seems to be hit with an empty object... Any help would be greatly appreciated.

I also tried using Postman to make the POST request and it worked fine. Could there be an issue with the information in the body?

Here's a screenshot of it working correctly:

https://i.sstatic.net/7KUlC.jpg

Answer №1

It appears that the format of your POST request to the server is incorrect.

The postman request suggests that your server expects data in x-www-form-urlencoded format, which should look similar to this:

Id=5&Name=Test

However, your Angular application seems to be sending data in a JSON format like this:

{"Id":5,"Name":"Test"}

To resolve this issue, you can either stop using JSON.stringify in your client-side code and construct the form data query style (while ensuring the Content-Type is set to x-www-form-urlencoded), or add a FromBodyAttribute to your back-end action like so:

public async Task<JsonResult> Post([FromBody]SubCategory subCategory)

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

Maximizing Performance of JSON.stringify in Angular

In my Angular app, I have a service that retrieves JSON data from an API. At times, this API sends back over 400 records (JSON Objects). When I directly access the endpoint in my browser, it takes around 5 seconds to load all the JSON data onto the page. ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Are you looking to denormalize your ngrx store and configure selectors?

I am currently dealing with a complex data structure in an ngrx project. It consists of nested parent objects with multiple levels of child objects, which are normalized on the server side. Here is an overview of my store's layout: rootObjs: { le ...

Tips for utilizing innerHTML in TypeScript code within an Angular 2 application

Is there a way to utilize innerHTML from TypeScript code in Angular 2 RC4? I'm facing an issue: I need to dynamically add precompiled HTML code when a specific button is clicked. For instance: TypeScript code private addHTML() { // not sure how ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Is it possible to verify if a boolean value is false within each object in an array?

I am working with an array that contains multiple objects. Each object has a 'Position' and 'Mandatory' field: quesListArray = [ {Position: 1, Mandatory: false}, {Position: 2, Mandatory: true}, ...

Use an extension module in a Node.js script

I am currently working on integrating babylon.js into my Node.js Angular application. Current Integration Process 1) I have installed the babylon.js npm repository in my project's node modules using npm install --save babylonjs. The image below i ...

Tips for utilizing generated *.d.ts files

I have been utilizing a Visual Studio 2017 extension called TypeScript Definition Generator to automatically create TypeScript interfaces for my MVC-ViewModels. Despite trying various similar tools, they all seem to result in the same output (*.cs.d.ts-Fil ...

Is there a way to implement depth-first retrieval in rxjs using the expand method?

Currently, I am engaged in a project utilizing Angular 7, Typescript, and RxJS 6.3.3. In this project, I am working with RxJS Observables and relevant operators to handle hierarchical collections of objects obtained from an http server that interfaces with ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

``Registering a basic service: A step-by-step guide

Considering a shift to a generic service layer for my system. public interface IAbcService<TEntity> where TEntity : class public class AbcService<TEntity> : IAbcService<TEntity> where TEntity : class Initial attempts have not been suc ...

Trigger Angular Animation when there is a modification in the DOM element's appearance or styling

I've been working on implementing a fade-in animation in my Angular App that triggers every time the background changes, but I'm facing some challenges with it. Here's the relevant code snippet: HTML: <div @fadeIn [style.backgroundImag ...

Ways to access the values of checkboxes that are initially checked by default

Recently, I was working on a project that involved multiple checkboxes. My goal was to have the checkboxes pre-checked with values in the form (using reactive form). Users should be able to unselect the boxes as they wish and the data would be stored accor ...

Safari does not display disabled input fields correctly

I have designed a simple angular-material form with various inputs that are organized using angular flex-layout. The form displays correctly in all browsers except for Safari on iOS devices. The problem in Safari arises when loading a form that contains d ...

Prevent modal from closing when clicking outside in React

I am currently working with a modal component in react-bootstrap. Below is the code I used for importing the necessary modules. import React from "react"; import Modal from "react-bootstrap/Modal"; import ModalBody from "react-bootstrap/ModalBody"; impor ...

Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present ...

When attempting to send an email with nodemailer, an error message popped up saying "setImmediate is not defined."

let transporter = nodemailer.createTransport({ host: "sandbox.smtp.mailtrap.io", port: 2525, auth: { user: "xxxxxx", pass: "xxxxxx" }, tls: { rejectUnauthorized: false } ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

Learning to implement the latest language features in JavaScript on older runtimes using TypeScript

Currently, I am faced with a dilemma in my TypeScript project involving the use of flatMap. The issue arises from the fact that this project needs to be compatible with Node.js versions as old as v10, which do not support flatMap. I had assumed that TypeS ...

Enhancing the appearance of the Mui v5 AppBar with personalized styles

I am encountering an issue when trying to apply custom styles to the Mui v5 AppBar component in Typescript. import { alpha } from '@mui/material/styles'; export function bgBlur(props: { color: any; blur?: any; opacity?: any; imgUrl?: any; }) { ...