Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          if(req.status != 200){
            console.log('non 200 status');

The this.http in my code refers to a service that I have injected into the system:

post(url, payload){
    return this.http.post(url, payload, { observe: 'response' });
  }

In this code, I am observing the entire response.

Although I am able to log the request and receive information about the httpresponseerror object's status, my code seems to be not functioning correctly as expected.

core.js:14597 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8080/api/user/user", ok: false, …}
error: {failcontext: "That email is already in use"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://127.0.0.1:8080/api/user/user: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "http://127.0.0.1:8080/api/user/user"
__proto__: HttpResponseBase

I am puzzled why my code is not behaving as intended. Any help would be appreciated!

Answer №1

The solution was found by adding the error listener to the code:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          console.log(req);

        },
        (err: any)=>{
          if(err.status != 200){
            console.log('non 200 status');
          }
        }
      );

Answer №2

Make sure to include the observer in your HTTP request

return this.http.post(
    this.apiUrl, { observe: 'response' });
}

This allows you to retrieve the entire response object instead of just the data.

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

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

Angular - ngx-Pagination malfunctioning in an unexpected manner

Currently in my Angular project, I am setting up server-side pagination using ngx-bootstrap-pagination with ASP.NET Core-6 as the backend. This is the service implementation: getPaymentStatus(): Observable<IPaymentStatus[]> { return this.http.get& ...

Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. T ...

Using Angular to convert JSON data to PDF format and send it to the printer

Currently, I am retrieving JSON data from an API and now need to convert this data into a PDF format for printing. I am encountering an issue where the CSS styling for page breaks is not rendering properly within my Angular component. When I test the same ...

Optimal strategies for managing request and response within an Express application

I've developed a REST API using express (and typescript) with the following structure: app.ts routes controllers models Query: Where is the ideal location to handle and construct requests/responses? Is it in routes or controllers? I am ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

What is the reason for TypeScript's decision to lazily evaluate constrained class generics?

I am experiencing confusion with the TypeScript declaration provided below. class C<T extends {}> { method() { type X = T extends {} ? true : false; // ^? type X = T extends {} ? true : false; // Why is X not `true`? ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

Explore the functionalities of RxJS filter operators by applying them to a stream of arrays

Is it possible to work with a stream of arrays, such as filtering, and then emit the arrays again without concatenating the elements of the arrays or using regular array operators? For example, if I have an observable containing a single array, I can perfo ...

"An issue arises as the variable this.results.rulesFired is not properly

I am faced with a set of table rows <tr *ngFor="let firedRule of splitRules(results.rulesFired); let rowNumber = index" [class.added]="isAdd(firedRule)" [class.removed]="isRemove(firedRule)" ...

Implementing authentication using http.post in Angular 2 with Django-Rest-Framework

I have spent more time than I care to admit trying to find a solution to this particular issue, but unfortunately, I am unable to resolve it on my own. Currently, I have a Django-rest-api that I set up using this tutorial. I can successfully interact with ...

The triggering of routing in Next.js is not established by useEffect

I'm facing an issue with my Next.js dynamic page that uses routing based on steps in the state. The route is supposed to change whenever a step value changes, like from null to "next" or back. However, the useEffect hook doesn't seem to be reacti ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

The sendKeys function in Selenium seems to be missing some characters when inputting text

Currently, I am working on test automation using Java, Selenium, and Chrome. Our developers recently made an upgrade from AngularJS to Angular2 for our UI. Ever since the upgrade, I've been facing an issue where sendKeys is inputting incomplete charac ...

Is it possible to configure npm to publish to an organization different from the one automatically detected from package.json?

We are looking to implement a process in our open source project where all Pull Requests will be published to npm using CI/CD. To reduce the potential for supply chain attacks, we aim to deploy to a separate organization. Can this be achieved without makin ...

Tips for mock nesting a repository in TypeORM?

I'm struggling to figure out how to stub a nested Repository in TypeORM. Can anyone assist me in creating a sinon stub for the code snippet below? I attempted to use some code from another Stack Overflow post in my test file, but it's not working ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Tips for adjusting the color of sorting arrows in the Header of a Data table using Angular Material

I'm having trouble changing the header color of the sorting arrows in the Angular Material data table. You can view the data table here. Currently, the sorting arrows are gray by default and I want to change them to white. Despite my efforts, I haven ...