Getting Image from API in Angular 4/5+?
Solution 1:
You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
Solution 2:
angular 5 :
getImage(id: string): Observable<Blob> {
return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}