简体   繁体   中英

Bind image from service in angular 6

I have an endpoint that provides me an image based on certain parameter. It's not an image url, its a plain image. So when i hit the endpoint in postman, in response, i receive an image (JPG).

I do i receive this image in a variable and bind it in tag of HTML?

All the questions have solution for mapping an image url to image, whereas mine is an image which i have to display in UI.

show-image-component.ts

this.appservice.getImage().subscribe((image) => {
    console.log(image);
 }
)

service.ts

getImg() {

 return this.httpClient.get('xyz.com', {headers: this.httpHeaders});

 }

How should i display the image i receive in image variable on HTML?

You can find detailed steps on how to achieve this in this blog post -> https://blog.mikehodnick.com/angular-download-image-blob-and-bind-to-img/

TL;DR - The long and short of it is you need to do the following:

(Please note this was implemented using Angular 4.1.3 )

  1. Get your image using http
  2. Set the response type to be BLOB so that we get the image in binary format
  3. Sanitize the blob response
  4. Assign the sanitized response to a member variable in your service.ts file
  5. Assign the member variable to the src attribute in your view in HTML
  6. Profit :D

Sample Code from the above-linked blog post:

view

<img [src]="imageData">

component

import { Component, OnInit } from '@angular/core';
import { Http, ResponseContentType } from '@angular/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

  imageData: any;

  constructor(private http: Http, private sanitizer: DomSanitizer) {
  }

  ngOnInit() {
    const imageUrl = 'http://where.your.images/are/hosted.jpg';

    this.http.get(imageUrl, {
      responseType: ResponseContentType.Blob
    })
      .toPromise()
      .then((res: any) => {
        let blob = new Blob([res._body], {
          type: res.headers.get("Content-Type")
        });

        let urlCreator = window.URL;
        this.imageData = this.sanitizer.bypassSecurityTrustUrl(
            urlCreator.createObjectURL(blob));
      });
  }

}

On Angular 6+ you could try this

On the service:

import { DomSanitizer } from '@angular/platform-browser';
import { HttpClient, HttpHeaders } from '@angular/common/http';

...

constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
}

getFile(url: string): any {

  return this.http.get(url, {
    responseType: 'blob'
  })
  .pipe(
    map((res: any) => {
      const urlCreator = window.URL;
      return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(res));
    })
 );
}

On the component:

const imgSrc: any;

downloadFile(uri) {
  this.service.getFile(uri).subscribe((res: any) => {
  this.imgSrc = res;
});

}

On the template:

<img id="myImg" [src]="imgSrc" alt="Attached file" style="width: 100%">
<button type="button" (click)="downloadFile('YourFile/Url')" id="imgBtn">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM