1

After doing a big deal of research on the topic I decided to ask in here. I am getting all null properties to the POJO/Model which is supposed to get values from the JSON I am posting from the Angular 2 Front end. Here is the rest controller method:

@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 

The following is the POJO/Model/Hibernate Entity:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private Long id;

private String firstname;
private String lastname;
private String department;

public Employee(){}

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}

The following is the Angular 2 Service method:

updateEmployee(emp:Employee){
  let url: string = "http://localhost:8080/api/employees/update";
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  return  this.http.post(url, {emp}, {headers: headers, withCredentials: true }).map(res => res.json());
}

and the Employee interface of Angular 2:

export interface Employee{
  id: number;
  firstname: string;
  lastname: string;
  department: string;
}

What am I doing wrong? I have searched for similar issues but none I found applies to my case. Thank you!

mrkachariker
  • 411
  • 4
  • 9

2 Answers2

0

Try annotating the method with @ResponseBody

Which would become:

@ResponseBody
@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 
Community
  • 1
  • 1
AME
  • 2,262
  • 6
  • 19
  • 39
0

You need to serialize the javascript object before sending it. Try:

this.http.post(url, JSON.stringify(emp), {headers: headers, withCredentials: true }).map(res => res.json());
alfcope
  • 2,327
  • 2
  • 13
  • 21
  • Thanks but I tried that already, and it made no difference...I believe the problem is on the back-end and not the front end. – mrkachariker Mar 06 '17 at 13:06
  • So, is the payload being sent right for sure? Check the network tab at the browser console. – alfcope Mar 06 '17 at 13:54
  • I just solved it, actually it wasn't mapping because of the curly brackets I was putting around the emp variable. Thanks a lot for your help – mrkachariker Mar 06 '17 at 14:41