How to get an image from an api rest using HttpClient in angular 4

1

I have the following service in my angular application:

getProviderPhoto(id:string){
    return this.http.get(this.apiUrl+"/"+id+"/images", {responseType: "blob"});
  }

And I need to convert the response of this service, which in this case is a Blob, to a png file to show it in my HTML component.

This I try to do through the following method:

 createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    this.photo = new File([image],"foto.png",{ type: 'image/png' });
    reader.readAsDataURL(this.photo);
    reader.onload = (event: any) => {
      this.image=event.target.result;
      console.log(this.image);
    }
 }

When calling this service you can see in the console the representation in base 64 of the obtained image:

data:image/png;base64,ImlWQk9Sd.....N caracteres.

This is the part where I call my service:

this.providerService.getProviderPhoto(this.email).subscribe(profilePhoto=>
        {
          this.createImageFromBlob(profilePhoto);
        });

This is the part of my HTML component where the image is displayed

<div class="profile-image center" [ngStyle]="{ 'background-image': 'url(' + image + ')'}"></div>

image is a local attribute that I have in my component where I save the image. In summary what this component does is simply make a request get to my api to get the profile picture of a user and show it But the problem is that it does not work ... So how can I get an image from an api rest and show it in my HTML?

    
asked by AlejoDev 16.05.2018 в 01:33
source

0 answers