My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code:
res= this.CS.postcompetenze(this.comp)
This is the servlet code:
postcompetenze(raw: any):boolean{
var comp = '{' +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"descrizione"'+':'+'"'+raw[1]+'" }'
const obj = JSON.parse(comp);
var res=this.http.post<any>('http://localhost:8080/postcompetenza', obj).subscribe(
(val) => {console.log("POST call successful value returned in body", val);
})
if(res!= null)
return true
else
return false
}
And here is my endpoint in the backend:
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // adds a competence
public competenza addCompetence(@RequestBody competenza comp) {
return cs.addCompetence(comp);
}
I would like to receive the status code response (200,300,400, etc.) along with or instead of the returned object.
Edit:
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // adds a competence
public ResponseEntity<?> addCompetence(@RequestBody competenza comp) {
try {
competenza response = cs.addCompetence(comp);
return ResponseEntity.status(HttpStatus.OK).body(200);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(409);
} catch (BadRequest e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(400);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(500);
}
}
This is how my backend looks now and my front-end:
postcompetenze(raw: any){
var comp = '{' +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"description"'+':'+'"'+raw[1]+'" }'
const obj = JSON.parse(comp);
var res=this.http.post<any>('http://localhost:8080/postcompetence', obj).subscribe(
(val) => {console.log("successful insertion "+JSON.stringify(val))
if(val == "200")
this.toastr.success("employee inserted correctly","SUCCESS");
else
this.toastr.error("employee not inserted","ERROR")
},
(error) => {
console.error('error caught in component '+error)
this.toastr.error("employee not inserted","ERROR")
}
)
I'm working on this because I need to display a toastr for success or error. With this code, I can only get the success toast, but I'm having trouble displaying the error toast. Any help would be appreciated. Thank you.