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?
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:
Your problem might lie in this.masterService
which seems to be proxying your http client and swallows some properties?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With