0

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);
    }

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

This was useful to me only that I had to map the params with @RequestParam instead of @RequestBody in the Spring Rest backend.
0

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());

12 Comments

I added this JSON.stringify(user), but it still not working I get null value
What is the sent payload you can see from the Network tab of DevTools?
You mean the user parameter of the method in your Spring controller?
user in the parameter is the User.ts if i can say is the DTO in client side among the properties I have in user is email and password so i need to transfer this two attributes to the server to compare login
data => this._user = data; when i do that the values of _user becomes null because data is also null so why data is null
|
0
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']); } ); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.