Angular HTTP request use response

June 15, 2021 · 2 min readLucian Ciobanu
Tags:AngularRxJS

On my current project, after I make a POST request to the database to save a an entry, the API returns OK 200 and an empty object when the save has been done correctly. In this scenario, I had to find a way to trigger a call to the database to refresh the already displayed records so that the just made change would be visible. In order to do this, I came across an object which can be bassed when making the http request so that on subscribe I can read and use the response. Here goes:

service.ts

// ...

public saveUpdate(params: ParamsType[]): Obserable<any> {
  return this.http.post<any>(environment.apiURL + '/endpointLink', params, { observe: 'response' })
    .pipe(
      catchError(handleError<any>())
    )
}
  

component.ts

// [...]

this.service.saveUpdate(params).subscribe(
  (res) => {
    if (res.status == 200) {
      this.reloadTable();
    }
  },
  (err) => {
    alert(err.status);
  }
 );

So the trick is to add the optional { observe: 'response' } paramater to the http post request and we can use res and error as arguments for the following functions.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery