以角度 6 绑定来自服务的图像 [英] Bind image from service in angular 6

查看:22
本文介绍了以角度 6 绑定来自服务的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个端点,可以根据特定参数为我提供图像.这不是图片网址,而是普通图片.因此,当我在 postman 中到达端点时,作为响应,我收到了一个图像 (JPG).

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).

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

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

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

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

 }

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

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

推荐答案

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

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 - 总而言之,您需要执行以下操作:

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

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

(Please note this was implemented using Angular 4.1.3)

  1. 使用 http 获取图像
  2. 将响应类型设置为BLOB,以便我们获得二进制格式的图像
  3. 清理 blob 响应
  4. 将经过清理的响应分配给 service.ts 文件中的成员变量
  5. 将成员变量分配给 HTML 视图中的 src 属性
  6. 利润:D
  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

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

查看

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

}

这篇关于以角度 6 绑定来自服务的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆