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:
HttpClient
use?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?
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.
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