The post request using Angular's HttpClient is failing to send the correct information to the server

The data stored in the request variable in my code snippet is as follows:

{widgetName: "widgetName", widgetCriteria: "Activities", followUpDate: "1591727400000", uid: "someId"}

let request = JSON.parse(JSON.stringify(Object.assign(this.registrationForm.value, ...req)));
      delete request.widgetFIlterOptions;
      let uid = JSON.parse(window.localStorage.getItem("user")).uid;
      request.uid = uid; 
      this.openWindow = false;
      console.info("request-->", request);
      this.contactService.addWidget(request).subscribe(res=> {
        this.emService.updateWidgits();
      })

When invoking the addWidget() function/method, a post request is submitted. However, after the post request is sent, I am facing an issue with the absence of the "followUpDate" parameter in the received response from the ResetController class.

I am seeking assistance to resolve this matter. As a newcomer to Angular, I may have overlooked something crucial here.

addWidget(widget, data?) {

    console.info("widget-->", widget); // the followUpDate field exists here
    this.http.post(this.api.createWidget, widget).pipe(map(data => {
        console.info("data-->", data); // however, the followUpDate is not present in this data.
        let message = "Widget created successfully";
        data['data'] = this.filterWidgets(data).length > 0 ? this.filterWidgets(data): alert("No data Available");
        this.widgets.unshift(data);
        this.toastr.success(message);
    }),catchError(err => {
      this.toastr.error(err.error);
      return throwError(err);
    }));

The following excerpt showcases my RestController class:

@RestController
public class DashboardController {

    @Autowired
    Service service;

    @PostMapping(path = "createcriteria", produces = MediaType.APPLICATION_JSON_VALUE, consumes =  MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "create the deal", response = Dashboard1.class)
    public Dashboard1 saveCriteria(@RequestBody Dashboard1 dashboard1) {

         System.out.println(dashboard1); // here, the "followUpDate" field is missing
         return service.saveCriteria(dashboard1);
    }
}

Below is the structure of my Dashboard1 class:

@Document(collection = "Dashboard1")
@JsonInclude(Include.NON_NULL)
public class Dashboard1 {

    @Id
    @ApiModelProperty(notes = "The database generated product ID")
    private String id;

    @Field(value = "widgetname")
    private String WidgetName = null;
    @Field(value = "widgetcriteria")
    private String WidgetCriteria = null;
    @Field(value = "uid")
    private String uid = null;
    @Field(value = "activitytype")
    private String activityType = null;
    @Field(value = "contactname")
    private String contactName = null;
    @Field(value = "updateby")
    private String updateBy = null;
    @Field(value = "followUpDate")
    private String followUpDate = null;

    // Includes all getter, setter, and toString() methods below
}

Answer №1

There's no need to use JSON.stringify on the object. Just ensure that the attribute names in your JSON match those in your Spring class, and submit the pure object without stringifying it.

Answer №2

After debugging my code, I discovered the problem lied within my getters and setters. There was a discrepancy between the field name and the getter and setter names. While the field name was followUpDate , the corresponding getter and setter names were getFallowUpDate() and setFallowUpDate(String)

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

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

Converting JSON data to a relational format in SQL

This is in reference to a previous question: Is it possible to "unpivot" in SQL after data ingestion from JSON. If I have the following dataset stored in a SQL table, where the data was mistakenly inserted from a JSON file: X1AB_name X1AB_age Y ...

The NbDatePicker does not display certain Spanish names

One issue I'm facing is with the Nb-DatePicker component in my project. I tried using {provide: LOCALE_ID, useValue: "es-MX"} in my app.component to display it in Spanish. However, when February, April, May, August, or December are selected, ...

A guide on creating a JSON object from two lists using Python

Let's say we have two lists: table_headers = ['first_name', 'last_name'] table_data = ['John', 'Doe', 'Jane', 'Smith'] How can we transform them into a JSON object like this: json_data = { ...

Tips for asynchronously subscribing to an observable from an array in Angular

I am facing a scenario where I have an array containing IDs and I need to subscribe to observables for each ID in a sequential order. I attempted to use a foreach loop but the responses were not in the desired order. Then, I tried to implement a for loop a ...

Vue JS TypeScript component is unable to locate injected instance properties

Currently, I'm utilizing typescript alongside vue in my project. Within the app structure, there exists a service that acts as a global entity for all sub-components. I stumbled upon this native solution provided by Vue JS, which facilitates injecti ...

Using jq to convert a configMapKeyRef to a secretKeyRef

My deploy input is shown below { "apiVersion": "apps/v1", "kind": "Deployment", "spec": { "replicas": 1, "selector": { "matchLabels": { "io.kom ...

Transforming complex nested JSON structures into simple flat JSON using TypeScript and RxJS operators such as map, reduce, and filter

Is there a way to convert the following structure into a simpler one without using complicated foreach loops? It would be great if this can be achieved with existing JS-Libraries like RxJS for Observables, Lodash/Underscore or any similar library. Here is ...

Exploring TypeScript Decorators and the Intricacies of Circular Dependencies

Take a look at this code snippet that involves inter-dependent code using decorators. Let's walk through the workflow where the actual classes are passed for later use: The application imports and executes Parent.ts @Test(Child) triggers the import ...

Creating Helm charts configuration files using JSON data is a straightforward process

I am looking for a solution to create complex JSON using HELM templates. Below is an example of my template: apiVersion: v1 kind: ConfigMap metadata: name: test data: config.json: | { "test": "{{ $Value }}", "services": { {{- range $k ...

The issue with not being able to fetch videos from a channel using YouTube API v3

I have encountered an issue while trying to retrieve a user's list of videos from YouTube using PHP code. Despite my efforts, the "items" field appears empty. $apiKey = "MY-API-KEY"; $channel_name = "UCSzDPMGFGxDgM4YtNM4arTA"; $count ...

Ways to send a JSON object to a Node.js server

I am working on developing a hybrid mobile application with Node.js as the backend and MongoDB for saving data. My server is functioning properly, and I have set up routes to handle user requests. While I can retrieve data from my server using the GET met ...

Learn how to send a POST request in a loop using React

I've created a function to delete all elements in a table using the rowKeys array. The current contents of rowKeys are ["www.google.com", "www.youtube.com", "www.facebook.com"]. async onAfterDeleteRow(rowKeys) { for(let i = 0; i < rowKeys.leng ...

Prevent selection of future dates in Kendo UI Calendar Widget

Can someone please advise on a method to disable future dates (i.e., gray them out) in the Kendo UI Calendar widget? I've attempted hiding the future dates, but it doesn't look good. I've also tried different ways to gray them out without su ...

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

The @RequestParam annotation seems to be failing to retrieve a value

When a user inputs their phone number in my application, I want to check if that phone number is already in the database. To do this, I am using an onchange event to instantly send the phone number for validation. However, I am facing an issue where the da ...

The specified target "TypeScriptClean" is not present within the project

I'm facing some issues in Visual Studio 2017 Professional. Despite not having any TypeScript code in my solution, I am encountering numerous TypeScript-related errors during the build process. The main error message that keeps popping up is: The targ ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

How to transform a nested array into a JSON object using ActionScript 3

Although the native JSON.stringify method is available, it does not meet my specific requirements I am looking to convert the following [['user1',150],['user2',270],['user3',500]] into a correctly formatted JSON object {"u ...

Facing issues with setting Origin headers correctly in Spring Boot Spring Security 5.7.3

I have been struggling to configure minimal headers for CORS on the same machine but different ports. I am currently working with the latest versions of Spring Boot and Spring Security. Unfortunately, the documentation is lacking and the examples are not ...