Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient - Handle empty and non-empty responses

Assuming we have http: HttpClient, I would like to provide a service call wrapper method as follows:

public async post<T>(url: string, body: any): Promise<T> {
    // do some stuff

    const response = await this.http.post<T>(url, body, this.options).toPromise();

    // do more stuff

    return response
}

This works as expected for any T except void. The behavior I was hoping for (and am still looking to implement) is to not return any value (Promise<void>) when the server returns no response. I'm now wondering what the best way to implement this is without having a different function for empty response bodies.

I assume there's no way to disambiguate based on the generic type? I tried looking for ways to do that, but it seems there's no way to do it, which makes sense given what TypeScript does and how it works. Fwiw, the type would be available at the call-site (as in, I would be calling that method as service.post<void>(...) in the case I expect an empty response body).

One thing I was wondering is if I could always make it return a string (responseType: "text") and then parse the JSON manually. Then I could check the status and response string, if they were 200 and "" respectively I would know that I can return undefined. If that was the right way to go (and I'm not sure that it is) there are a few questions I have:

  1. Would manually parsing the JSON have a performance drawback?
  2. What method should I use to parse it? What does the HttpClient use?
  3. How would I make sure that error handling works the same as if it happened from within the HttpClient.post method? Ideally I wouldn't want it to deviate from the error mechanism inside of HttpClient.post.

Or is there another simple way that I'm missing to implement the desired method? Are any of my assumptions false?

like image 293
Stjepan Bakrac Avatar asked Sep 16 '25 23:09

Stjepan Bakrac


1 Answers

As it turns out this is only an issue if the server returns 200. If the server returns the "no content" status 204 (which is appropriate for an empty response body) then post returns null. I would have preferred undefined to distinguish from an actual null JSON response (since null is a valid JSON token), but it is what it is, and what it is is good enough for me.

like image 124
Stjepan Bakrac Avatar answered Sep 19 '25 15:09

Stjepan Bakrac