Bind image from service in angular 6

二次信任 提交于 2019-12-23 12:40:37

问题


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?


回答1:


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

}



回答2:


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">


来源:https://stackoverflow.com/questions/52484654/bind-image-from-service-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!