Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httpclient response is null when API returns a 204 status code

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?

like image 649
user66875 Avatar asked Dec 06 '18 14:12

user66875


1 Answers

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?

like image 115
B12Toaster Avatar answered Sep 19 '22 13:09

B12Toaster