Reputation: 13
I use Angular 5 + Spring Boot. The problem is that I can not send information to my rest controller by post method. I do not get any error either from the client side or from the server side. Below the code you will see that I make get method which works correctly. Let me apologize for my Е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);
}
}
And Angular post Method
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;
}
Upvotes: 1
Views: 4277
Reputation: 648
Where are you calling subscribe on the post function? I don't see it here. As http post returns an observable, you must subscribe to it to make the call.
http.post(....).subscribe(response => <DO SOMETHING WITH IT>);
Upvotes: 2
Reputation: 2894
This might not be all of the errors on your code but this is something I noticed.
Your Java @PostMapping
doesn't specify what it should be expected to receive and what it should produce in return.
@PostMapping(value = "save", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
For Angular 5, you're using Angular 4 service Syntax, I thought they changed that on 5.
Upvotes: 0