使用@RequestBody将Angular2中的对象发布到Spring RestContoller

时间:2016-06-25 13:00:21

标签: spring angular angular2-http

客户端和服务器之间的连接正常,并且在服务器上调用了正确的函数addEpic。问题是,只在服务器上创建了一个新的Epic实例,但不使用客户端的属性。 @RequestBody似乎是个问题。不应该自动将@RequestBody从json数据转换为指定的类? Epic是@Entity类的根本问题是什么?

也可能是客户端错误地生成了正文。 console.log(正文)显示:

{"epic":{"id":"f97d885a-410f-fa6d-7adc-291e63d35341", "name":"OurName"}}

但我的招摇 - ui显示身体模型shema:

{"id":"string", "name":"string"}

客户端

  addEpic(epic:Epic):Observable<any> {
    let body = JSON.stringify({epic});
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this.http.post(url + "addEpic", body, options)
      .map(this.extractHeader)
      .catch(this.handleError);
  }

export class Epic {
  id: string;
  name: string;
}

服务器

    @RequestMapping(value="/addEpic", method = RequestMethod.POST)
    public ResponseEntity<Void> addEpic(@RequestBody Epic epic) {

        // Here it seems that constructor of epic is called and a new instance is created
        epicRepository.saveAndFlush(epic);

        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Epic implements Serializable {
    private static final long serialVersionUID = -670305953055479441L;

    @Column
    private String id;

    @Column
    private String name
}

1 个答案:

答案 0 :(得分:3)

您的实体Epic有两个属性&#39; id&#39;并且&#39; name&#39;。 在JSON中:

{"id":"string", "name":"string"}

这正是Swagger向您展示的内容。

所以你的客户做错了,你应该像那样创建JSON

let body = JSON.stringify(epic);

只需删除史诗般的超级{}。

相关问题