繁体   English   中英

在角度6中绑定服务中的图像

[英]Bind image from service in angular 6

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

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

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

show-image-component.ts

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

服务

getImg() {

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

 }

如何在HTML的image变量中显示收到的图像?

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

TL; DR-长或短是您需要执行以下操作:

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

  1. 使用http获取图像
  2. 将响应类型设置为BLOB,以便我们以二进制格式获取图像
  3. 消毒斑点反应
  4. 将已清理的响应分配给service.ts文件中的成员变量
  5. 将成员变量分配给HTML视图中的src属性
  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));
      });
  }

}

在Angular 6+上,您可以尝试一下

关于服务:

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

在组件上:

const imgSrc: any;

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

}

在模板上:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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