My backend currently sends back an image in response. When I access this backend through a browser, the image is displayed without any issues.
The response type being received is 'image/jpeg'.
Now, I am exploring different methods to fetch this image using Angular HttpClient.
If I simply make a GET call, I notice that the image is successfully downloaded in the Network tab of the browser.
However, when attempting to retrieve the image with Angular, I encounter an error:
https://i.sstatic.net/wwoan.pngThe code snippet looks like this:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThumbnailService {
private thumbnailUrl = 'http://localhost:8080/thumbnail';
constructor(private http: HttpClient) { }
public findOne(classifiedId: number): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'image/jpeg',
})
};
return this.http.get<any>(`${this.thumbnailUrl}/${classifiedId}`, httpOptions);
}
}
Upon investigation...
- Angular seems to be trying to parse the response as JSON due to the specified responseType
- There are multiple method overloads available for parsing responses based on their types
- Even when trying to use Blob as the return type:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThumbnailService {
private thumbnailUrl = 'http://localhost:8080/thumbnail';
constructor(private http: HttpClient) { }
public findOne(classifiedId: number): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'image/jpeg',
})
};
return this.http.get<Observable<Blob>>(`${this.thumbnailUrl}/${classifiedId}`, httpOptions);
}
}
I still face the same issue.
It appears that the Blob type has certain expectations which my current setup does not meet...
Is there a simpler way to fetch an image using Angular HttpClient? Could there be something crucial that I am overlooking?
When I set the headers and responseType together, it leads to a compilation error - regardless if the response type is any or Blob:
Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'. Types of property 'responseType' are incompatible. Type 'string' is not assignable to type '"json"'.