gpt4 book ai didi

javascript - 以 Angular 6 绑定(bind)来自服务的图像

转载 作者:太空狗 更新时间:2023-10-29 17:58:18 25 4
gpt4 key购买 nike

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

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

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

显示图像组件.ts

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

service.ts

getImg() {

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

}

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

最佳答案

您可以在这篇博文中找到有关如何实现此目的的详细步骤 -> 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. 将成员变量分配给 HTML View 中的 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));
});
}

}

关于javascript - 以 Angular 6 绑定(bind)来自服务的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52484654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com