'unable to load image file from server in angular
i am sending an image file named figure.png from flask api and it is working fine. i have checked it in postman. now here is the angular code -> chart-component.ts->
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-bar-chart2',
templateUrl: './bar-chart2.component.html',
styleUrls: ['./bar-chart2.component.css']
})
export class BarChart2Component implements OnInit {
imgsrc!: Observable<any>;
uploadApiUrl = "http://127.0.0.1:5000/graph"
getimage(){
this.imgsrc = this.http.get(this.uploadApiUrl)
console.log("imgsrc: " + this.imgsrc)
}
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.getimage()
}
}
the html code->
<p>Min-Max analysis</p>
<img src={{imgsrc}} alt="no image" id="barChart2" style="position: relative; height:60vh; width:120vw">
the image does not load.
console window->
imgsrc: [object Object]
GET http://localhost:4200/[object%20Object] 404 (Not Found)
can someone help with whats going on?
Solution 1:[1]
this.http.get
returns an Observable
and img
tag expects a string as src
.
You need to accept the Blob
from the API, create a URL from that blob, and then pass it as src
to your img
tag. Something like :
imgsrc!: string | ArrayBuffer | null;
sub!: Subscription;
uploadApiUrl = "http://127.0.0.1:5000/graph"
constructor(private http: HttpClient) { }
getimage(){
this.sub = this.http.get(this.uploadApiUrl, {
headers: { 'Content-Type': 'application/octet-stream'},
responseType: 'blob'
}).subscribe((src) => {
// Get the blob
const reader = new FileReader();
reader.readAsDataURL(src);
reader.onloadend = () => {
// result includes identifier 'data:image/png;base64,' plus the base64 data
this.imgsrc = reader.result;
}
});
}
ngOnInit(): void {
this.getimage()
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}
HTML:
<p>Min-Max analysis</p>
<ng-container *ngIf="imgsrc">
<img src={{imgsrc}} alt="no image" id="barChart2" style="position: relative; height:60vh; width:120vw">
</ng-container>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mordor619 |