i have a component that calls a servlet, that servlet send a post http request to the back-end(i use spring boot), i would like the back end to return the status fo the post that i sent earlier; that's my code: here i call the servlet, as you can see i would like to have the status error in a var called res
res= this.CS.postcompetenze(this.comp)
that's the servlet:
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 that's my endpoint in the backend: cs.addCompetenza(comp) is a function that calls another function from jpa, this method returns the objecrt competenza.
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // aggiunge una competenza
public competenza addCompetenza(@RequestBody competenza comp) {
return cs.addCompetenza(comp);
}
so again i would like to have the status code response (200,300,400,...)with or instead of the returned object. edit:
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // aggiunge una competenza
public ResponseEntity<?> addCompetenza(@RequestBody competenza comp) {
try {
competenza response = cs.addCompetenza(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);
}
}
that's my backend now, my front-end:
postcompetenze(raw: any){
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("andata "+ JSON.stringify(val))
if(val == "200")
this.toastr.success("dipendente inserito correttamente","SUCCESSO");
else
this.toastr.error("dipendente non inserito","ERRORE")
},
(error) => { //Error callback
console.error('error caught in component '+error)
this.toastr.error("dipendente non inserito","ERRORE")
}
)
i'm doing all of this because i need to show a toastr of success or error, with this code i can have only the success toast,i don't understand why i can't get the error toast; thanks for your help