我使用Angular 5 + Spring Boot。问题是我无法通过post方法向我的休息控制器发送信息。 我从客户端或服务器端都没有收到任何错误。 在代码下方,您将看到我使get方法正常工作。 让我为我的Еnglish道歉。
Spring Entity {Dish}
@Entity
@Table(name = "DISHES")
@Data
public class Dish implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "NAME", unique = true)
@NotNull(message = "Ястието трябва да има име.")
@Size(min = 3, max = 30, message = "Името на ястието трябва да е между 3 и 30 символа.")
private String name;
@Column(name = "DESCRIPTION")
@NotNull(message = "Описанието на ястието не може да е празно.")
@Size(min = 3, max = 300, message = "Описанието на ястието трябва да е между 3 и 30 символа.")
private String description;
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL ,mappedBy = "dish")
@JsonBackReference
private List<DishCounter> dishCounters;
}
Angular Entity {Dish}
export class Dish {
constructor(public id?: number, public name?: string, public description?: string) {
}
}
Spring Rest Controller {Dish}
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/dish")
public class DishRestController {
private static final Logger logger = LoggerFactory.getLogger(DishRestController.class);
private final DishService dishService;
@Autowired
public DishRestController(final DishService dishService) {
this.dishService = dishService;
}
@GetMapping("/all")
public ResponseEntity<List<Dish>> getAllDishes() {
logger.info("Rest controller find all dishes");
List<Dish> dishes = dishService.getAllDishes();
return ResponseEntity.status(HttpStatus.OK).body(dishes);
}
@PostMapping("/save")
public ResponseEntity<Void> saveDish(@RequestBody Dish dish) {
dishService.saveDish(dish);
return new ResponseEntity<>(HttpStatus.OK);
}
}
和Angular post方法
save(dish: Dish): Observable<Dish> {
let result: Observable<Dish>;
result = this.http.post(this.saveDishUrl, dish)
.map((resp => {
console.log(resp);
return resp;
}))
.catch(e => {
console.log(e);
return Observable.throw(e);
});
console.log(result);
return result;
}
答案 0 :(得分:1)
你在哪里打电话订阅帖子功能?我在这里看不到它。当http post返回一个observable时,你必须订阅它以进行调用。
http.post(....).subscribe(response => <DO SOMETHING WITH IT>);
答案 1 :(得分:0)
这可能不是您代码中的所有错误,但这是我注意到的。
您的Java @PostMapping
没有指定应该接收的内容以及它应该返回的内容。
@PostMapping(value = "save", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
对于Angular 5,您使用的是Angular 4服务语法,我认为他们在5上改变了它。