从 Angular 6 服务中绑定图像

Rah*_*rma 5 html javascript angular angular5 angular6

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

我是否可以在变量中接收该图像并将其绑定到 HTML 标签中?

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

显示图像组件.ts

this.appservice.getImage().subscribe((image) => {
    console.log(image);
 }
)
Run Code Online (Sandbox Code Playgroud)

服务.ts

getImg() {

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

 }
Run Code Online (Sandbox Code Playgroud)

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

小智 2

您可以在此博客文章中找到有关如何实现此目标的详细步骤 -> 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">
Run Code Online (Sandbox Code Playgroud)

成分

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

}
Run Code Online (Sandbox Code Playgroud)