The Angular http.post function seems to be returning null responses consistently, without any actual data being received

When making a post call in Angular using Http.post, I am sending jsonData as a parameter with the following formatted data. However, every time I receive a response as null. Could you please review my code and let me know if there are any mistakes? Here is a sample of the code I have tried:

let jsondataItems :any =[];

var jsonData = [
    {
        "empId": 11234,
        "salary": "98763",
        "test1id": "9897989",
        "test2id": "657453",
        "test3id": "4456",
        "month": "AUG-19"
    }]

this.http
      .post<empData>(url, jsonData)
      .subscribe((res) => {
        this.jsondataItems = res;
        console.log("res" + this.jsondataItems); // receiving null
        console.log("res" + JSON.stringify(this.jsondataItems)); // receiving null
        console.log("Processed successfully!!!"); // console -- working
      });
  }



interface empData {
  empId: number; //1234
  salary: string; //"3456"
  test1id: string; //""5678"
  test2id:string; //"5643"
  test3id:string; // "4533"
  month: string; //"JAN-20"
}

Answer №1

Below is a suggested solution:

 import { HttpHeaders } from '@angular/common/http';
        
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json'
          })
        };
   
    let jsonDataItems :any =[];
    
    var jsonData = [
        {
            "empId": 11234,
            "salary": "98763",
            "test1id": "9897989",
            "test2id": "657453",
            "test3id": "4456",
            "month": "AUG-19"
        }]
    
    this.http
          .post<empData>(url, jsonData,httpOptions)
          .subscribe((res) => {
            this.jsonDataItems = res;
            console.log("res" + this.jsonDataItems);
            console.log("res" + JSON.stringify(this.jsonDataItems));
            console.log("Processed successfully!!!"); 
          });
      }
    
    
    
    interface empData {
      empId: number;
      salary: string; 
      test1id: string; 
      test2id:string; 
      test3id:string; 
      month: string; 
    }

You can use the same http options, just include the observe: response. The header should be HttpHeaders from the http client library, for example: headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded').

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

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Ways to restrict the values allowed in a TypeScript type?

I have a requirement: type AllowedKeys = 'a' | 'b' | 'c' ... and now I want to define a type where the key has to be one of the values in AllowedKeys. For example: type MyType = { a: number; b: string; c: boolean; d: {} / ...

Sorting information by class titles in AngularJS

Working with angularjs, take a look at my view code : <div style="width:70px;"> Show Online <input type="checkbox" ng-model="showonline" /> </div> <div ng-repeat="user in use ...

Angular 5 Dilemma: Exporting UI Components without Locating Template

My current project involves developing UI Components that will be used in various web projects within the company. Our plan is to publish these UI components as an npm package on our local repository, and so far, the publishing process has been successful. ...

Angular @Input set function not being activated during unit testing

Within my Component @Input('price') set setPrice(price) { this.price = price; this.modifyTotalAmount(); } Unit Testing (component.spec.ts) it('should execute function ', () => { spyOn(fixture.componentInstance, ' ...

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

Lexicaljs utilizes debounce to receive editor state JSON and text content in a React project

What I Need I am looking to retrieve the editor state in JSON format, along with the text content of the editor. Moreover, I prefer to receive these values in a debounced manner, as described here. The reason I want to obtain the values in a debounced wa ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

Building a single-page app optimized for mobile viewing with Foundation framework

Currently facing an issue with the scaling of the viewport on certain mobile devices when loading new content via ng-include in our responsive website built on Foundation. The problem arises as the width of the page breaks, leading to horizontal scrolling. ...

Dropping challenging shapes in a block-matching game similar to Tetris

I'm currently working on a game similar to Tetris, but with a twist. Instead of removing just one line when it's full, I want to remove all connected pieces at once. However, I've run into a roadblock when trying to implement the hard-drop f ...

What is a way to retain the value of a variable after a request, while starting off with a different value on the initial load?

In my Flask application, users have the option to choose a specific time period with a start date and an end date. When the page initially loads, I want the start date to default to the first day of the current month and the end date to be the current day. ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

The issue of Ejs partial header and footer file only functioning in one file and not the other (both at the same directory level)

I'm in the process of setting up a view page for a post on the main page of a website. Both pages share the same header and footer files, located at the same directory level. However, while one page is functioning correctly, the other is not. The erro ...

Linking a button to a (click) event within HTML content fetched from the backend

Hey there, I'm facing a scenario where I have an angular service that sends a HTTP request to the backend for some HTML code. Once the HTML is received, I'm inserting it into the component's HTML using <div [innerHTML]="..."/>. The iss ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

React: Implementing Material-UI Typography with custom inline spacing

Take a look at this code snippet: <Typography className={classes.welcomeMessage} variant="h1"> A <span className={classes.redText}>smart nation </span> approach to <span className={classes.redText} ...

Picking out specific elements from a component that is rendered multiple times in a React application

One of the challenges I face involves a component called card, which is rendered multiple times with different data. Here's how it looks: { this.state.response.reminders.map((item,i=0) =>{ return <Card key={i++} reminder={item} deleteRem={th ...