2017-03-06 20 views
0

在做了大量關於這個話題的研究之後,我決定在這裏問一下。我得到了POJO/Model的所有null屬性,它應該從我從Angular 2前端發佈的JSON中獲取值。下面是其餘控制器方法:spring啓動映射null屬性到JSON的POJO請求來自angular2

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

以下是POJO /型號/休眠實體:

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

以下是角2服務方法:

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

和Angular 2的員工界面:

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

我在做什麼錯?我已經搜索了類似的問題,但沒有發現適用於我的案例。謝謝!

+0

嘗試與註釋@ResponseBody –

+0

方法它仍然是相同的......所有的屬性都爲空 –

+1

我只是解決了它,其實那是因爲大括號我周圍的推杆沒有映射emp變量。非常感謝您的幫助 –

回答

0

您需要在發送之前進行序列化的JavaScript對象。嘗試:

this.http.post(url, JSON.stringify(emp), {headers: headers, withCredentials: true }).map(res => res.json()); 
+0

謝謝,但我已經嘗試過,並沒有區別...我相信問題是在後端而不是前端。 –

+0

那麼,有效載荷是否被正確發送?在瀏覽器控制檯檢查網絡選項卡。 – alfcope

+0

我剛解決了它,實際上它並沒有映射,因爲我使用了大括號來放置emp變量。非常感謝你的幫助 –

0

嘗試註釋的方法與@ResponseBody

這將成爲:

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

關於參數emp仍然是一樣的。其所有屬性均設置爲空。 –