YK mar
YK mar

Reputation: 677

Send Data from client angular2 to server spring 'POST'

I dont have any error but I get data null in the server side can you help for by giving an example thks

this is my client service

import {Injectable, Inject} from "angular2/core";
import {Http, Headers} from "angular2/http";
import 'rxjs/add/operator/map';
import {User} from "../User/User";


@Injectable()
export class loginService {

    constructor(private _http:Http) {

    }

    login(user) {

        // var creds = "username=" + "khalil" + "&password=" + 3;   .map(res=>res.text());
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post('http://localhost:8080/login', user, {
                headers: headers
            })
            .map(res=>res.json());

    }

this is my component where I call login method

import {Component, Inject} from 'angular2/core';
import {Router} from "angular2/router";
import {loginService} from "./login.service";
import {HTTP_PROVIDERS, Http} from "angular2/http";
import {User} from "../User/User";
import {ControlGroup, FormBuilder, Validators, Control} from "angular2/common";

@Component({
    selector: 'login',
    templateUrl: '../dev/login/login.html',
    providers: [HTTP_PROVIDERS, loginService]
})

export class loginComponent {
    public _user:User;
    loginForm:ControlGroup;

    constructor(private _router:Router,
                private _loginService:loginService,
    private _formBuilder:FormBuilder) {


        this._user = {
            firstName: '',
            lastName: '',
            tel: '',
            email: '',
            creationDate: new Date(),
            compteMatriculaire: '',
            enabled: false,
            password: '',
            structure: ''
        };

    }

    login() {
        console.log("email"+this._user.email);
        this._loginService.login(this._user).subscribe(
            (data:User) => {
               this._user = data;
            },
            error => alert('Erreur ' + error),
            () => {
                console.log("finished  " + this._user.email + "   " + this._user.password);
                //this._router.navigate(['Home']);
            }
        );
    }

this is my form page

<div class="container">

    <form #loginForm="ngForm" (ngSubmit)="login()" class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="email" class="sr-only">Email</label>
        <input type="email"  ngControl="email" [(ngModel)]="_user.email" #email id="email"  class="form-control" placeholder="email" required autofocus>
        <label for="password" class="sr-only">Password</label>
        <input type="password" ngControl="password" [(ngModel)]="_user.password" #password id="password"  class="form-control" placeholder="Password" required>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> Remember me
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
</div>

and this is my controller

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User_khalil> login(User_khalil user) {
        System.out.println("------- " + user.getEmail() + user.getPassword());

        User_khalil u = userRepository_khalil.findOneByEmailAndPassword(user.getEmail(), user.getPassword());
        if (u != null) {
            return new ResponseEntity<User_khalil>(user, HttpStatus.OK);
        }
        return new ResponseEntity<User_khalil>(user, HttpStatus.OK);
    }

Upvotes: 0

Views: 2900

Answers (3)

waltR
waltR

Reputation: 31

public ResponseEntity<User_khalil> login(@RequestBody User_khalil user)

@RequestBody is the key with this solution.

The other option (without @RequestBody):

  this._http.post('http://localhost:8080/login', user, {
  headers: headers,
  params: new HttpParams().set('username', 'Khalil'),
})

In this way, you send the POST request to the URL /api/login?username=Khalil.

I recommend the first option with @RequestBody.

Upvotes: 3

YK mar
YK mar

Reputation: 677

login() { console.log("email"+this._user.email); this._loginService.login(this._user).subscribe( data => { console.log(data); this._user = data; }, error => alert('Erreur ' + error), () => { console.log("finished " + this._user.email + " " + this._user.password); //this._router.navigate(['Home']); } ); }

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202148

You forgot to convert your object as string using the JSON.stringify function:

return this._http.post('http://localhost:8080/login', 
        JSON.stringify(user), { // <------
            headers: headers
        })
        .map(res=>res.json());

Edit

You could try the following:

return this._http.post('http://localhost:8080/login', 
        JSON.stringify({
          email: user.email,
          password: user.password
        }), {
            headers: headers
        })
        .map(res=>res.json());

Upvotes: 0

Related Questions