Reputation: 85
In an angular app that uses HttpClient service, The code below works fine:
this.http.get(myUrl, {responseType: 'json'})
I need to send the responseType as a dynamic parameter, something like:
this.http.get(myUrl, { responseType: (condition ? 'json' : 'blob') })
or like:
let options = { responseType: 'json' };
if (condition)
options = { responseType: 'blob' };
this.http.get(myUrl, options)
but typescript does not like it, and shows an error: No overload matches this call
What am I doing wrong and how can I achieve this?
Thanks!
Note: This Type "json" | undefined not satisfied by "json" in Angular HttpClient
does not meet my requirement, but helps me to correct the code:
const options: { responseType: "json" } = { responseType: "json" };
const optionsBlob: { responseType: "blob" } = { responseType: "blob" };
this.http.get(myUrl, condition ? options : optionsBlob)
yet, compiler is not satisfied, and shows the previous error.
Upvotes: 1
Views: 1077
Reputation: 10954
HttpClient.get()
has overloads based on the response type: https://angular.io/api/common/http/HttpClient. You can see that providing a different response type calls a different function. So this.http.get(myUrl, options);
is ambiguous, the compiler does not know which function you are referring to. Instead, just call the correct overload as part of your condition.
if (condition) this.http.get(myUrl, { responseType: 'blob' });
else this.http.get(myUrl, { responseType: 'json' });
Alternative with HttpClient.request()
instead.
const responseType = condition ? 'json' : 'blob';
const request = new HttpRequest('GET', myUrl, { responseType });
this.http.request(request);
Upvotes: 1