Is there a way to retrieve the status code from the HttpClient module in Angular?

Can you find out how to retrieve the status codes for all requests using the HttpClient method?

callingAPI() {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('Authorization', `Bearer ${this.token}`);

    this.http.post("URL",
      {
        "dataToSend": "data"
      }, {
      headers: headers
    }).subscribe(response => {

      console.log(response);

    },
      (error: HttpErrorResponse) => {
        if (error.status === 403) {
         console.log("Caught 403 status code");
        }
      }

      
    )
  }

Is there a way to determine the status code of an HTTP request that returns 202, 200, or other statuses?

Answer №1

Make sure to include observe: 'response' in the options parameter. This allows you to access the entire response within your subscription.

  public fetchData(): void {
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('Authorization', `Bearer ${this.token}`);

    this.http.post<HttpResponse<any>>(
      'URL',
      {
        dataToSend: 'data',
      },
      {
        headers: headers,
        observe: 'response',
      },
    ).subscribe(
      (responseData: HttpResponse<any>) => {
        if (responseData.status === 200 || responseData.status === 202) {
          console.log(`Received a successful status code: ${responseData.status}`);
        }
        console.log(`Response body: ${responseData.body}`);
      },
      (error: HttpErrorResponse) => {
        if (error.status === 403) {
          console.error('Caught 403 status code');
        }
      },
    );
  }

For more information, check out: https://angular.io/guide/http#reading-the-full-response

Answer №2

To make API calls in Angular, utilize HttpErrorResponse and HttpResponse from the package '@angular/common/http'

makeApiCall() {
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  headers = headers.set('Authorization', `Bearer ${this.token}`);

  this.http.post<HttpResponse<any>>('URL', { data }, { headers }).subscribe(response => {
      console.log(response.status) // log status code
  }, (error: HttpErrorResponse) => console.log(error.status))

}

Answer №3

For those utilizing HttpClient library, below is a sample code snippet:

this.httpClient.post(myEndpoint, requestBody, { headers : customHeaders, observe: 'response' }).subscribe(
  response => {
    console.log(JSON.stringify(response, null, 2));
  },
  error => {
    console.error(error.errorMessage);
});

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

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Angular Dropdown Menu

When working with Angular, I encountered an issue with creating a drop down. Despite having a list of items, only the first item is displayed in the drop down menu. <div class="form-group"> <h4>Projects</h4> <div *ngFor="let ...

Angular throws an error when attempting to access a property that is undefined

I created the following angular template: <section class="section"> <div class="container"> <form [formGroup]="testForm"> <div class="columns is-multiline"> <div class="column is-2"> ...

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

Utilizing a single Angular 2 app to incorporate various components on a single page

Can you guide me on how to dynamically render a section of HTML from a child component to a parent component in Angular 2? The concept is to create a main layout where different sections can be replaced or customized by child components based on specific r ...

How can the creation of directories for services be avoided in angular-cli?

For those of us using angular-cli, starting from version 1.4, they made the decision to create separate directories not just for components (which is understandable) but also for services that only consist of 2 files: the service file and the test file. ...

Angular2 - Easily update form fields with just a click

I have a form that retrieves data from a service and presents it in the following format: @Component({ selector: 'profile', template: `<h1>Profile Page</h1> <form [ngFormModel]="myForm" (ngSubmit)="onSubmit()" #f="ngFor ...

Utilizing Angular for Webcam Integration

After trying out this code snippet: <video autoplay playsinline style="width: 100vw; height: 100vh;"></video> <script> navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then(stream =&g ...

Encountering TypeScript error TS2339 while mocking a React component with Jest

When attempting to mock a React component using Jest, I encountered an issue where TypeScript was not recognizing the mocked methods and showing a TS2339 error. Below is the test code snippet causing the problem: jest.mock('./features/News/News' ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

Minimize property names with Webpack

Our Vue 2.x.x application, written in typescript, needs to be structured into modules such as /users, /articles, /reports, following a micro frontend architecture. We are looking for a solution that allows us to load these modules dynamically based on use ...

retrieve the key associated with a translated value using ngx-translate

Using @ngx-translate along with localize-router has posed a challenge for me. I am unable to resolve a valid slug from a localized URL. For example, if the translation of 'about' is 'asd', then: routerLink="about/{{'about' ...

"Exploring the Application of Post Parameters in REST Services

I am in the process of setting up rest services for posting data. I was wondering if it's more efficient to post data using http form elements or to send all the data as one json string and parse it on the server side. Is there a preferred method or a ...

Tips for preventing HTTP calls within chained Angular subscriptionsHere are some strategies to prevent

I am faced with a scenario where I have to call an HTTP service to retrieve data, and then based on that data, I need to immediately make another HTTP request. Typically, I would use pipe along with switchMap to accomplish this task efficiently. However, t ...

How can I customize a currency directive in AngularJS using filters?

My goal is to enhance user experience by allowing input in custom currency values like '1.5M' instead of 1500000, and '1B' instead of 1000000000 on an input form dealing with large numbers. To achieve this, I've created a FormatSer ...

Issue with file uploading in Angular 9 as the uploaded file is not being added to the

I've set up a form group in the HTML of my Angular 9 app that includes an upload feature for files. The file upload works fine when calling the handleFileInput function, as I can confirm from the console log output. However, even though the file gets ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Guide on Incorporating an Image into Jhipster Angular

I was having trouble displaying an image in my JHipster project. Even though I placed the image in the component folder as well as in the folder src/main/webapp/content/images, I was only seeing the alt tag "agenda" on the browser. In my homecomponent.ht ...