httpclient response is null when API returns a 204 status code
Asked Answered
I

1

7

I have a rest endpoint /Products/latest which returns 204 in case there are no products, and the following generic angular service:

  getFromAPI(url: string) {
    const params = new HttpParams();

    return this.http
        .get(url, { params: params })
        .catch((err: HttpErrorResponse) => {
            console.error(`Backend returned code ${err.status}, body was: ${err.error}`);                  
            return Observable.of([]);
        });
  }

and

 getFromAPI() {
        return this.masterService.get('/Products/latest').map((res: Response) => {
            if (res.status === 204) {
                return Observable.of([]);
            } else {
                return res;
            }

        });
    }

However, when the servies results a 204 code, I'm getting the following error:

TypeError: Cannot read property 'status' of null

How can this be happening? Why is the whole response null if the API responds with a 204?

Inexperience answered 6/12, 2018 at 14:53 Comment(1)
try it in the catch methodCuddle
K
12

First of all, I would say it is strange (or wrong) that your backend is returning a 204 for an empty collection instead of a 200 together with an empty list.

Using Angular7 and RxJS6 I constructed a test case where my backend is configured as follows:

[HttpGet("/Products/latest")]
public async Task<NoContentResult> list()
{
  return NoContent();
}

In frontend using:

public getFromAPI() {
  return this.httpClient.get('/Products/latest', { observe: 'response' }).pipe(
    switchMap(res => res.status === 204 ? of([]) : of(res))
  ).subscribe();
}

And the response clearly contains a status despite not having a body:

enter image description here

Your problem might lie in this.masterService which seems to be proxying your http client and swallows some properties?

Kraul answered 6/12, 2018 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.