Retrieving Status Text from an Angular 8 Http Service

My application includes a service that sends a POST request to a server:

addPerson(person:PersonDTO) :Observable<any> {
  return this.httpClient.post<any>(this.urlBase + 'Persons', person);
}

When subscribing to the service in a component:

this.valueService.addPerson(person).subscribe((data) => {
   this.responseCode = data.statusText;
   console.log(this.responseCode)
});

I want to display the response code on the console. However, if there is an error, the code stops before reaching the console.log. And if there is no error, undefined appears on the console.

Answer №1

Welcome to the platform!

By default, when making a request to your API, you will receive the response body only. To access additional information such as status codes, you must include an observe option in your request:

addNewUser(user:UserModel) :Observable<any> {
  return this.httpClient.post<any>(this.apiUrl + 'users', user, {observe: 'response'});
}

Your current subscription is set up for handling the successful case only (the next scenario). To handle errors, you should add another callback for potential errors:

this.userService.addNewUser(user).subscribe(
  (data) => {
   this.statusCode = data.status;
   console.log(this.statusCode)
  },
  (error) => console.error(error)
);

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

Determine if Toggle Accordion is Expanded by Checking HTML Attribute Using Selenium

I am working with an HTML Angular Material Accordion component. When it is expanded, the class mat-expanded is added. <mat-expansion-panel _ngcontent-ng-cli-universal-c931="" data-qa="product" class="mat-expansion-panel ng- ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

Is there a way to incorporate a button with row span in ag-grid within an Angular project?

In my project, I have incorporated ag-grid. I successfully implemented a cell renderer to display a button in the "action" column. The button appears on each row and functions properly when clicked. Now, for my second task, I am looking to include a butto ...

Error in Typescript: Unable to locate module with proper type declarations

Recently embarking on a new nodejs project with typescript, I utilized Typings (https://github.com/typings/typings) to install reference files for node v4.x and express v4.x. Outlined in my setup are the following versions: Node - v4.2.6 Typescript - v1 ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

different ways to retrieve component properties without using inheritance

In order to modify certain properties of components after login, such as the "message" property of HomeComponent and the "age" property of UserComponent, I am unable to inherit the component class. What are some alternative methods to achieve this? Authen ...

The input values passed to "onChange" are not compatible with "NativeSyntheticEvent<TextInputChangeEventData>"

I'm fairly new to React Native and encountered an issue while trying to implement the following code snippet: <TextInput style={styles.input} onChange={(text) => setPontoValue(text)} /> This error message ...

The rxJS observable is failing to reach the subscribe method

I'm struggling to set up a simple observables system with Angular 2 and RxJS. My understanding is that the do operator is for side effects, and the subscribe() function is where you handle the results from the observable. In my scenario, the Compone ...

Insert items into an array at a specific index in typescript

Using the map function, I am adding elements to array arr1. Is there a way to specify the starting index position in typescript? For example: If I want to add elements from the 3rd index position of the array, with the first two indices holding a value of ...

Is there a way to adjust the dimensions of my Angular npm slider?

This snippet shows the Angular code I came across this npm slider on npm.js Struggling to adjust the margin of the images as they are sticking, also unsure about modifying the size and other elements using https://www.npmjs.com/package/ng-image-slider. A ...

Is it possible to specify the timing for executing Typescript decorators?

One issue I've encountered is that when I define a parameterized decorator for a method, the decorator runs before the method itself. Ideally, I'd like the decorator to run after the method has been called. function fooDecorator(value: boolean) ...

Prevent hover functionality on an Angular highchart bar graph

Is it possible to individually select bars in an angular highcharts stacked bar chart? I'm looking to either select a single stacked bar or disable the hover effect entirely. I came across some custom code that allows me to select bars for each cate ...

``Why Ionic 3 Popover Sizes Should Adapt to Different Screen

Currently in my Ionic 3 project, I am utilizing a popover with a set height using the following code snippet: editOpty(rw){ let popover = this.editOptyPopup.create(EditOptyPopoverComponent, rw, { cssClass: 'edit-opty-popover'}); popover ...

The creation of an Outlook 365 add-in using Angular8 presents challenges when attempting to delete a cookie that was generated with ngx

I have developed an Office 365 add-in for Outlook. The add-in is built using Angular8 and I am utilizing ngx-cookie-service to store my authentication token information in a cookie. Despite being able to install the add-in, store the auth token in the co ...

Is it better to pass private state along with parameters to functions, or should functions directly access the private state?

My Angular application presents a scenario that I believe can be applicable to other frameworks and scenarios as well: public export class FooComponent { private userId: number; constructor(private readonly authService: AuthService) { } ngOn ...

Hello everyone, can someone provide guidance on integrating Spring Boot session with an Angular project?

Can anyone provide guidance on utilizing a Spring Boot session in an Angular project? I am looking to send the login and password via POST request in the following image Click here for image description ...

Protractor enables horizontal scrolling for a Div element

My struggle to scroll to the right persists despite all attempts I experimented with various solutions, but none seem to work await browser.executeScript('arguments[0].scrollIntoView(true)',element.getWebElement()) The issue still remains unr ...

Manage a particular path that does not utilize the hash symbol

My dilemma involves a URL: www.example.be/#/ I am determined to retain the hash. Upon receiving an ill-fated redirection to wrongPath/#/, my desire is to redirect it to /#/; unfortunately, the router fails due to the presence of the hash. I yearn for t ...

The RxJS mergeMap operator: The inner observable fails to execute

My goal is to upload multiple files, but before the upload can proceed, I need to send a POST request to get a personId. This personId will be used to link the uploaded files in the backend system. The postOnboardingRequestDto$ function successfully creat ...