0

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();
  }

1 Answer 1

1

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%2Fapp%2Fapp.component.ts

Sign up to request clarification or add additional context in comments.

1 Comment

I managed to solve it, but I only used promise. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.