Issues implementing error handling for Angular POST request

Viewed 46

For some reason my Angular code can't correctly handle error conditionals for a POST request.

For context, the relevant call is in a component.ts:

this.crazyService.addSomething(stringifiedContent).subscribe(
data => {
          console.log(data);
          this.showSuccess();
          setTimeout(() => {
            this.dashboardRedirect();
          }, 2750);
        }
)

In the 'crazyService' the code is

addSomething(something: any): Observable<any> {
    const headers = { 'content-type': 'application/json' };
    const body = JSON.stringify(something);
    return this.http
      .post<any>(this.relevantUri, body, { headers, observe: 'response' })
      .pipe(
        catchError(err => {
          console.error(err);
          throw err;
        })
      );
  } 

The POST request works fine, however for some reason the console.log(data), this.showSuccess() and timeOut don't work here.

Whereas when I do this in my component:

this.crazyService.addSomething(stringifiedContent).subscribe( hello => {
console.log(hello);}
, data => {
          console.log(data);
          this.showSuccess();
          setTimeout(() => {
            this.dashboardRedirect();
          }, 2750);
        }
)

It enters the data part and does the things I want whereas in the previous example it doesn't seem to enter that block.

Why is this the case? And how can I fix this so that I can have a case for when the POST request is successful, and another for when there is an error?

1 Answers

Fixed - turns out I had an issue in the Django backend. I sent a string as the HTTPResponse for the 201 in my backend instead of JSON. Angular parses it as JSON which causes the response to be an error, which is why it didn't enter into the place where I wanted it to enter.

Related