I would like to call an API endpoint which returns a document of type: content-type image/png I use RapidAPI: https://rapidapi.com/apidojo/api/divanscore/ This is the endpoint: players/get-image
How can I display the image returned by the previous API endpoint in html?
This is the player.service:
public GetPlayerImage(id: number): Promise<any> {
return this.http.get<any>('https://divanscore.p.rapidapi.com/players/get-image?playerId=' id, {
'headers': {
'x-rapidapi-host': 'divanscore.p.rapidapi.com',
'x-rapidapi-key': 'XXXX'
}}).toPromise();
}
CodePudding user response:
Convert the blob. Then sanitize it and embed it to dom. Sorry I could not use rapidApi example, I didn't have an API key or the player id's. But I hope this helps:
<img [src]="currVerifiedLoanOfficerPhoto">
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Download image blob and use on template';
currVerifiedLoanOfficerPhoto: any;
constructor(private http: HttpClient, protected sanitizer: DomSanitizer) {}
ngOnInit() {
this.http
.get(
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Angular_full_color_logo.svg/250px-Angular_full_color_logo.svg.png',
{ responseType: 'blob' }
)
.pipe(switchMap((blob) => this.convertBlobToBase64(blob)))
.subscribe((base64ImageUrl: string) => {
console.log(base64ImageUrl);
this.currVerifiedLoanOfficerPhoto =
this.sanitizer.bypassSecurityTrustResourceUrl(base64ImageUrl);
});
}
convertBlobToBase64(blob: Blob) {
return Observable.create((observer) => {
const reader = new FileReader();
const binaryString = reader.readAsDataURL(blob);
reader.onload = (event: any) => {
// console.log('Image in Base64: ', event.target.result);
observer.next(event.target.result);
observer.complete();
};
reader.onerror = (event: any) => {
console.log('File could not be read: ' event.target.error.code);
observer.next(event.target.error.code);
observer.complete();
};
});
}
}
Here is a working example: https://stackblitz.com/edit/read-image-from-url-and-convert-it-in-base-64-t98e2b?file=src/app/app.component.ts