Is there a way for me to receive the status code response from my backend server?

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.

Answer №1

If you want to retrieve the HttpStatus from the BackEnd response, ensure to include {observe: "response"} in the request parameters instead of the body.

Next, utilize a pipe along with a map function. Within the map function, extract the Http status and return your desired object for subscription. (I hope this explanation is clear)

this.http.get("https://jsonplaceholder.typicode.com/posts/1", {observe: "response"}).pipe(map(value => {
      //Here you can analyze the status or any other request details required (headers, response code, response body, etc.)
      console.log(value.status);
      return value.body; //returning just the body or any other information needed for subscription.
    })).subscribe(data => {
      //Here you have access to the body content.
      console.log(data);
    });

Additional tip:

For best practices, refer to the Java Naming Convention

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...

How can I pull all data from an array using MongoDB query?

I have multiple arrays, but I am only interested in extracting the content related to "PIZZAS." Can anyone advise me on the appropriate query to achieve this? https://i.stack.imgur.com/wHolE.png ...

The teleport-controls feature is currently not functioning properly in VR mode with Aframe version 0.8.2

Having an issue with the teleport-controls under aframe 0.8.2. When in VR mode using Vive, only the curve appears after touching the trackpad of the controller, but the camera position does not change. However, in flat mode, both the curve and camera posit ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Executing a jQuery code within a WordPress theme

I have been attempting to implement the following script within the header.php file of a Wordpress website: <script> jQuery(function($) { jQuery('[href=#membership]').attr( 'data-menu-top', '500' ); }); ...

Are there any find all functions available in JavaScript that are built-in?

I frequently work with arrays in JavaScript, and I am facing an issue with the function .find() as it only returns the first occurrence. I need a way to get all occurrences if there are multiple. Below is my code: const condition = [ { info_p ...

Steps for deactivating a textbox upon checkbox activation

When I try to implement the instructions from the textbook, I'm encountering an issue where clicking on the checkbox doesn't disable the textbox on my website. <form action="#"> Billing Address same as Shipping Address: <input ...

Display <video> component using Angular 2

When attempting to display videos sourced from an API link, I encountered a problem where only the player was visible without the actual video content. The navigation controls of the player were also unresponsive. Interestingly, when manually inputting the ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

Error encountered: EPERM when attempting to rename a directory in Node.js unexpectedly

There is a requirement for me to remove the Backup folder, rename the processor as Backup, create a Processor folder again, and send a response to the user. The code I am using for this task is as follows: fsExtra.remove('app/Backup', function(e ...

Changing the visibility of a button based on a checkbox in JavaScript - here's how

Just starting out with JS and working on a react project. I need to toggle the visibility of a button from false to true when a checkbox is checked. Here's my code, I believe the logic is correct but it's not updating the UI. Any suggestions are ...

Examining for a TypeError with Typescript and Jasmine

In my current project, I am faced with the challenge of writing unit tests in Typescript for an existing library that was originally written in plain JS. Most of our page logic is also written in plain JS. Some functions in this library throw exceptions if ...

Exciting Angular feature: Dynamic Titles

I am working with an <i> tag <i class="actionicon icon-star" [ngClass]="{'yellow' : data.isLiked}" (click)="Like(data)" aria-hidden="true" title="Liked"></i> In my current set ...

issue related to prototypejs event handlers and event triggering

Currently, I am in the process of learning both the prototype framework and javascript as a whole. My current task involves refactoring some existing code to generate HTML from data within a class by utilizing an event listener. Despite my efforts, I am en ...

JQuery Accordion SubMenu/Nested Feature malfunctioning

I have successfully implemented a JQuery Accordion on my website and it is functioning properly, opening and closing as expected. However, I am facing an issue when trying to add a submenu within the accordion. The submenu does not work as intended and lac ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

Searching for corresponding items in multi-dimensional arrays using Javascript

For my project in Javascript, I am facing the challenge of matching entire arrays. In this scenario, I have a userInput array and my goal is to locate a similar array within a multi-dimensional array and display the match. var t1 = [0,0,0]; var t2 = [1,0, ...

An issue arose when trying to implement react-router within a multi-step registration process

While working on my multi-step registration form, I encountered an error when implementing react router. Clicking on the personal info link led to the following console errors: "Uncaught TypeError: Cannot read property 'ownerName' of undefined" ...