Receiving NULL data from client side to server side in Angular 2 + Spring application

I'm currently working on a project that involves using Angular 2 on the client side and Spring on the server side. I need to send user input data from the client to the server and receive a response back. However, I'm encountering an issue where the 'loginDetailsDTO' is coming up as null on the server side.

If anyone has any suggestions on how to resolve this issue, please let me know. Your help would be greatly appreciated!

Thank you in advance for any assistance provided.

Below you can find a sample of the code snippets involved:

user.component.ts

import { UserService } from './user.service';
import { UserLogin } from './userLogin';

login(value: UserLogin) {
     this.UserService.login(value)
         .subscribe(data => console.log(data));
}

user.service.ts

import { UserLogin } from './userLogin';

login(loginDetails: UserLogin) {
    return this.http
        .get(this.loginUrl, JSON.stringify(loginDetails))
        .map(res => res.json());
}

userLogin.ts

export class UserLogin {
    userName: string;
    password: string;
}

userController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<LoginResponse> login(LoginDetailsDTO loginDetailsDTO){

    LoginResponse loginResponse = new LoginResponse();
    loginResponse.setResponseCode(LoginResponse.VALID_USER);

    return new ResponseEntity<LoginResponse>(loginResponse, HttpStatus.OK);
}

LoginDetailsDTO.java

public class LoginDetailsDTO {

    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Answer №1

For sending login data to the backend, it is recommended to use a POST request. Here's an example implementation:

login(loginCredentials: UserLogin) {
      return this.http
      .POST(this.loginEndpoint, JSON.stringify(loginCredentials))
     .map(res => res.json());
}

In the backend, make sure your controller is set up like this:

    @RequestMapping(value = customEndpoint , method = RequestMethod.POST)
    public @ResponseBody ResponseEntity authenticate(@RequestBody LoginDetailsDTO) {
        //magic
    }

It's worth mentioning that Spring handles /login POST requests by default. It's a good practice to create a customized endpoint like /authenticate.

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

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

Execute the MongoDB query with the option to disable locks: nolock

Hey there, Currently, I am executing the evaluation script using Node.js by setting nolock to true in order to disable the global lock. The same evaluation script is also being run in Java with nolock set to true. String jsFunction = "function(){" ...

Discovering the best approach to utilizing Font Awesome 6 with React

Required Packages "@fortawesome/fontawesome-svg-core": "^6.1.1", "@fortawesome/free-solid-svg-icons": "^6.1.1", "@fortawesome/react-fontawesome": "^0.1.18", "next": " ...

Issue with implicitly assigning 'any' type to overloaded variadic generic function

We have some code snippets for you to review: export type actions = { abort: () => void; back: () => void; next: () => void; resume: () => void; }; class Sabar { public use<T1>(fn: (arg1: T1, ctx: object, actions: actions) =&g ...

What is the role of the "prepare" function in AWS CDK constructs?

TL;DR: What is the role and purpose of the prepare(): void method in AWS CDK's Construct class? When and how should it be utilized or avoided? The information provided about prepare() states: prepare() function is called after child constructs have ...

Modeling graph nodes and edges within a UML diagram

What would be the most effective way to represent the relationship between a graph edge class and a node class in a UML class diagram? In my usual practice, I typically include two associations Edge->Node: one for the source node role and one for the d ...

Unidentified Controller Scope in Angular and TypeScript

I am struggling with my Angular 1.5 app that uses Typescript. Here is a snippet of my code: mymodule.module.ts: angular.module('mymodule', []).component('mycomponent', new MyComponent()); mycomponent.component.ts export class MyCont ...

The term 'components' has not been defined (no-undef)

Recently integrated Vue into an existing project and encountered a peculiar linting error: error: 'components' is not defined (no-undef) at src/App.vue:13:3: 11 | 12 | @Component({ > 13 | components: { HelloWorld }, | ^ 14 | }) ...

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

JVM malfunction during the execution of a Java program utilizing rJava library for integration with R

Recently, I started learning R programming and wanted to call an R script from my Java code using rJava in Eclipse. Below is a snippet of what my program looks like: package pkg; import org.rosuda.JRI.Rengine; import java.io.IOException; import org.rosuda ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

Encountering issues with utilizing global variables in Ionic 3

Using Ionic 3, I created a class for global variables but encountered an error Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError (http://localhost:8100/build/vendor.js:1590:86) at noProviderError Th ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default: class Car {...} class Bus {...} export default { Car, Bus } You can also easily export a type as default export default interface Airplane {...} However, exporting multiple types as default i ...

New approach in Typescript: Enhancement of child class with additional Event Listener overloads

One of my classes is structured like this: interface A extends EventEmitter{ on(event: "eventA", listener: () => void): this; } There is another class defined as follows: interface B extends A{ on(event: "eventB", listener: ...

Associating a JSON function with a specific URL path pattern

As I develop a Spring MVC application that includes a controller with 'RequestMapping'-annotated methods, among them a JSON method, I encounter an issue regarding serving static content. The current setup has the static content stored in webapps/ ...

Is a Truststore required for AWS IoT Java client?

I found it easy to specify the truststore in the documentation for the python client for AWS IoT, but I'm unsure how to do this with the java client. Can anyone provide guidance? myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH", "PRIVATE/KEY/PAT ...

Angular2 checkboxes for filtering data

I'm working with an Angular2 grid that showcases an array of Fabrics, each with its own color or fabric type properties. Right now, all Fabrics are displayed in the grid, but I need to implement a series of checkboxes for color and fabric type, along ...