Home > database >  Get the Status Text from a http Service - Angular 8
Get the Status Text from a http Service - Angular 8

Time:12-30

I have a service which sends a POST request to a server:

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

I subscribe to the service in a component:

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

I would like to print the response Code on the console. The problem is when there is an error the code stops before it comes to the console.log. And if there is no error undefined is displayed on the console

CodePudding user response:

Welcome here!

By default, the response is limited to the response body from your API. To get additional info like the status, you need to add an observe option with your request:

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

Basic subscription like yours means you are only dealing with the next use case. To deal with error, you need another callback for errors:

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