-1

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

pietro
  • 51
  • 8

1 Answers1

0

In order to get your HttpStatus from the BackEnd response, you have to put first {observe: "response"} into the request parameters(not in the body).

Then use the a pipe with a map into the map you can take your Http status and return whatever object you want, to the subscribe object. (I hope it does make sense for you)

 this.http.get("https://jsonplaceholder.typicode.com/posts/1", {observe: "response"}).pipe(map(value => {
      //Here you can check your the status or whatever request info you want to get(headers, response code,response body, type and ecc...) 
      console.log(value.status);
      return value.body; //returning just the body or whatever you wanna see into your subscribe object.
    })).subscribe(data => {
      //Here you have your body.
      console.log(data);
    });

A plus:

Take a look at the Java Naming Convention

xTheDoctah
  • 276
  • 1
  • 11
  • thank you for your answer, but please let me know if I have to do something in the backend too in order to get the response code, i was wandering if this code is ok even for the get request, and thanks again :-) – pietro Aug 15 '21 at 11:51
  • The code looks "good" should work, although I don't understand `res=this.CS.postcompetenze(this.comp)` , post the whole controller code. In the code you wrote @PostMapping, that service, will not work with a Get request. – xTheDoctah Aug 15 '21 at 13:20
  • By the way, the back end cannot know which is the HttpStatus, until you set an HttpStatus. By default spring its taking care of your response Status Code, if you wanna send a custom HttpCode just use a ResponseEntity, an example can be found here https://www.baeldung.com/spring-response-entity . – xTheDoctah Aug 15 '21 at 13:22
  • In the code you wrote `@PostMapping` , that service, will not work with a Get request. You have to use a `@GetMapping` or if you wanna use the same endpoint for 2 Http Method(Get and post for instance) you have to use `@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})` – xTheDoctah Aug 15 '21 at 13:27
  • but mine is a post request, not a get request, i'm editing the question due to explain better my problem – pietro Aug 16 '21 at 07:52