在角度6中绑定服务中的图像 [英] Bind image from service in angular 6
问题描述
我有一个可以根据某些参数为我提供图像的端点.它不是图像网址,而是纯图像.因此,当我在邮递员中到达终点时,作为回应,我会收到一张图片(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的image变量中显示收到的图像?
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)
- 使用http 获取图片
- 将响应类型设置为 BLOB ,以便我们以二进制格式获取图像
- 消毒斑点响应
- 将清理后的响应分配给您的
service.ts
文件中的成员变量 - 将成员变量分配给HTML视图中的
src
属性 - 利润:D
- Get your image using http
- Set the response type to be BLOB so that we get the image in binary format
- Sanitize the blob response
- Assign the sanitized response to a member variable in your
service.ts
file - Assign the member variable to the
src
attribute in your view in HTML - 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屋!