I struggled with the HTTP patch that Angular provides, noticed that the method patch(url, body, options)
- which has a lot of overloaded functions - only accepts hard coded parameter for HTTP options.
Hard coded example which works:
patchEntity(id: number): Observable<HttpResponse<string>> {
const url: string = `url-to-resource`;
const body: string = `[{"op":"replace","path":"/id","value":345}]`;
return this.httpClient.patch(url, body, {
headers: new HttpHeaders({'Content-Type': 'application/json-patch json'}),
observe: 'response',
responseType: 'text'
});
}
Outsourced HTTP options that is responding with the following error message:
Type Observable<ArrayBuffer> is not assignable to type 'Observable<HttpResponse<string>>
Type 'ArrayBuffer' is missing the following properties from type 'HttpResponse<string>': body, type, clone, headers, and 4 more.
patchEntity(id: number): Observable<HttpResponse<string>> {
const url: string = `url-to-resource`;
const body: string = `[{"op":"replace","path":"/id","value":345}]`;
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json-patch json'}),
observe: 'response',
responseType: 'text'
}
return this.httpClient.patch(url, body, httpOptions); // <--- errors occurs here
}
Seems, I'm missing some basic understanding of what's going on in Typescript or Angular.
Can somebody teach me why Angular do not let me outsourcing the HTTP options and the errors occur?
Thanks in advance
CodePudding user response:
observe
and responseType
are string unions, so you need to mark them as const
in your options object, otherwise Typescript will infer them as type string
.
const httpOptions = {
...
observe: 'response' as const,
responseType: 'text' as const
}
You can read more about it in the official docs, at the end of this section
Cheers