javascript - 以角度 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 的图像变量中显示我收到的图像?
解决方案
您可以在此博客文章中找到有关如何实现此目的的详细步骤 -> https://blog.mikehodnick.com/angular-download-image-blob-and-bind-to-img/
TL;DR - 总而言之,您需要执行以下操作:
(请注意,这是使用Angular 4.1.3实现的)
- 使用 http 获取图像
- 将响应类型设置为BLOB以便我们获取二进制格式的图像
- 清理 blob 响应
- 将净化后的响应分配给
service.ts
文件中的成员变量 - 将成员变量分配给
src
HTML 视图中的属性 - 利润: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));
});
}
}
推荐阅读
- swift - 我可以从 Appearance API 中选择退出课程吗?
- php - 如何在同一个 Amazon EC2 实例中安装多个 Apache?
- xamarin.forms - UWP:尝试打开页面时出现 AccessViolationException
- phpunit - Phpunit 错误“此 PHPDBG 版本不支持代码覆盖率”
- swift - 在字符串格式中跳过未使用的位置参数(Swift)
- symfony - 树枝模板上表单字段的 setValue
- java - 在 Java 8 中以简化的方式将地图的元素正确写入 CSV
- sql - 根据 Hive 中的条件连接表
- python - 径向基函数的图像超分辨率
- ios - iOS 如何处理恰好在背景之前发生的事件?