首页 > 解决方案 > 以角度 6 绑定来自服务的图像

问题描述

我有一个端点,可以根据某些参数为我提供图像。它不是图片网址,而是普通图片。因此,当我在邮递员中到达端点时,作为响应,我会收到一张图像(JPG)。

我是否在变量中接收此图像并将其绑定到 HTML 标记中?

所有问题都有将图像 url 映射到图像的解决方案,而我的问题是我必须在 UI 中显示的图像。

显示图像组件.ts

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

服务.ts

getImg() {

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

 }

我应该如何在 HTML 的图像变量中显示我收到的图像?

标签: javascripthtmlangularangular5angular6

解决方案


您可以在此博客文章中找到有关如何实现此目的的详细步骤 -> https://blog.mikehodnick.com/angular-download-image-blob-and-bind-to-img/

TL;DR - 总而言之,您需要执行以下操作:

(请注意,这是使用Angular 4.1.3实现的)

  1. 使用 http 获取图像
  2. 将响应类型设置为BLOB以便我们获取二进制格式的图像
  3. 清理 blob 响应
  4. 将净化后的响应分配给service.ts文件中的成员变量
  5. 将成员变量分配给srcHTML 视图中的属性
  6. 利润:D

上面链接的博客文章中的示例代码:

看法

<img [src]="imageData">

零件

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

}

推荐阅读