Struggling to successfully map angular model data to a Spring POJO class

I am currently having issues mapping an Angular model class to my Spring model class. When I try to do so, all the entities in the Spring model class show up as null. I have included the code snippets below that I used for mapping, but unfortunately, it fails to map the Angular model data to the Spring POJO class.

HeaderMappingDetails.java

public class HeaderMappingDetails{
    String Impressions;
    String Clicks;
    String Revenue;
    //getters and setters
}

headermappingdetails.ts

export class HeaderMappingDetails{
    public Impressions:string;
    public Clicks:string;
    public Revenue:string
}

add-client.component.ts

saveHeaders(){
   this.clientService.saveHeaders(this.headerMap).subscribe(
       res=>{
           console.log(res);       
       },error=>{
           console.log(error);
       }
   );     
}

client.service.ts

saveHeaders(mapHeaders:HeaderMappingDetails){

    let url = this.serverPath+'/user/saveHeaders';
    let tokenHeader = new Headers({
    'Content-Type' : 'application/json',
    'x-auth-token' : localStorage.getItem('xAuthToken')
 });
    console.log(JSON.stringify(mapHeaders));
    return this.http.post(
        url,JSON.stringify(mapHeaders),
        {headers :   tokenHeader}
    );

}

addClient.html

<form [hidden]="!showMapper" (ngSubmit)="saveHeaders()">
    <mat-form-field class="full-width">
        <mat-select placeholder="Map Impression As" [(ngModel)]="headerMap.Impression" id="Impression" name="Impression">
                <mat-option *ngFor="let option of mapper" [value]="option">{{option}}</mat-option>
            </mat-select>
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-select placeholder="Map Clicks As" [(ngModel)]="headerMap.Clicks" id="Clicks" name="Clicks">
            <mat-option *ngFor="let option of mapper"  [value]="option">{{option}}</mat-option>
        </mat-select>
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-select placeholder="Map Revenue As" [(ngModel)]="headerMap.Revenue" id="Revenue" name="Revenue">
            <mat-option *ngFor="let option of mapper"  [value]="option">{{option}}</mat-option>
        </mat-select>
    </mat-form-field>
    <button mat-raised-button type="submit" class="mat-primary">Save Mapped Headers</button>
</form>

HeaderMappingController.java

@PostMapping(value = "/saveHeaders")
public HeaderMappingDetails saveHeaders(@RequestBody HeaderMappingDetails headerMappingDetails) throws Exception {
    Integer clientId = Integer.parseInt(jedis.get("emailClientId"));
    boolean isSuccess = headerMappingService.saveHeaders(headerMappingDetails, clientId);
    return headerMappingDetails;
}

This is the response printed by Angular in my console

{"Impression":"Campaign","Clicks":"Budget","Revenue":"Budget"}

Answer №1

To begin with, it is important to follow Java language standards when naming variables. For instance, variables should start with a lowercase letter (only classes should have a capital first letter). Additionally, it is advisable to make all variables private:

public class HeaderMappingDetails{
    private String impressions;
    private String clicks;
    private String revenue;
    // getters and setters
}

Based on my experience, your Angular code appears fine, although I personally use it in a slightly different manner:

saveHeaders(mapHeaders: HeaderMappingDetails){
    let url = this.serverPath+'/user/saveHeaders';
    const headers: HttpHeaders = new HttpHeaders();
    headers.set("content-type", "application/json");
    headers.set("x-auth-token", localStorage.getItem('xAuthToken'));
    const options = {
      headers: headers
    };
    console.dir(mapHeaders);
    return this.http.post(url, mapHeaders, options);
}

You do not need to stringify the object in this scenario.

In your particular case, I would also suggest using an interface instead of an object for your TypeScript object:

export interface IHeaderMappingDetails {
    impressions: string;
    clicks: string;
    revenue: 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

Adonisjs latest version (v5) model creation command malfunctioning

Using Adonisjs v5 The controller command works fine with: node ace make:controller Posts However, the new model creation command is not working: node ace:make model Post When running the make model command, an error occurs: An error message stating &ap ...

Why are my animation states being shared among different instances of the component?

Why is the animation playing for both instances of the carousel component when interacting with just one call (e.g. clicking next or prev)? carousel.component.ts @Component({ selector: 'app-carousel', standalone: true, templateUrl: './c ...

Ways to make a chosen row stand out in an *ngFor loop?

Struggling to find a solution within Angular2 for setting a css class when selecting a row. I want to achieve this without relying on jQuery. <table class="table table-bordered table-condensed table-hover"> <thead> <tr> ...

Navigating the seas of automation with Selenium and Java: Uncovering the secrets of identifying and interacting

Struggling as a newcomer in the automation world, I've attempted various xpaths to pass my test without success. The specific challenge I'm facing is locating the element containing the text OPTIONS AND FILTERS. On the website , you'll notic ...

I had high hopes that TypeScript's automatic type inference for constructor parameters would do the trick, but it seems to have let

You can experiment with the given code snippet at the online playground to confirm it. Consider this code: class Alpha { private beta; constructor(b: Beta) { this.beta = b; } doSomething() { ...

Sorting TypeScript types by required properties first

Can anyone recommend a plugin or ESLint rule that can automatically sort types by assuming required fields come first, followed by optional fields? Here's an example before: type TExampleSorting = { title?: string; value?: number; text: string; ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Incorporating an alternate object array to update an array of objects: A

There are two object arrays, the main array and the temp array. The goal is to compare the main array with the temp array and update the values in the main array based on matching IDs. In this example, IDs 2 and 3 match in both arrays. Therefore, the valu ...

Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response. In Angular, I usually ca ...

Methods that are characterized by Java's object model and data types

Currently, I am in the process of developing an application that involves various classes representing entities within a virtual world. The World consists of an array of objects, all inheriting from a base class called Thing. class World { Thing[] myOb ...

Retrieving all records in Firestore that have access to their child documents

I'm attempting to retrieve all the documents from each child collection (ratings) and update the average rating in the foobar document. However, I am encountering an error in one of my callable functions: Unhandled error RangeError: Maximum call stack ...

Choose a row that does not have the checkbox selected

Currently, I am using the ag-grid library which can be found at https://www.ag-grid.com After experimenting with various grid options such as rowSelection: 'multiple', suppressRowClickSelection: true, and rowDeselection: true, I encountered an i ...

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Exploring the use of index signatures in TypeScript when working with React

I'm struggling to properly implement the index signature in this code. I have an enum and I need to loop through it to display some JSX on the screen. I understand the error message, but I'm having trouble resolving it in my code. The issue seems ...

Observing a class getter within Vue.js

The issue at hand I am facing a challenge in ensuring my page automatically updates when new data is available. I am using Ionic, and have a page that displays all the items collected by the user in a visually appealing manner using an ion-grid. To achiev ...

Exploring the concept of data model inheritance in Angular 2

In my Angular2 and ASP.NET Core project, I have set up the following: My C# .NET Core API returns the following classes: public class fighter { public int id { get; set; } public string name { get; set; } public datetime birthdate { get; set; } p ...

Is it possible to use Jenkins for testing the operational status of a VM (server)?

Is it possible to utilize Jenkins for testing the status of a VM (server) and ensuring it is up and running properly? With numerous VMs housing JBoss, LDAP, MySQL, among other components, I am seeking a way for Jenkins to ping a server to detect any potent ...

A guide on inputting values into multiple text fields within a table using Selenium

Is there a way to populate multiple text fields within a table using Selenium? Take a look at the example below: https://i.sstatic.net/01tUt.png I attempted the following method, but I encountered an issue with an InvalidElementStateException. List< ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...