我有一个根据特定参数为我提供图像的端点。它不是图像网址,而是纯图像。因此,当我在邮递员中到达终点时,作为回应,我会收到一张图片(JPG)。
我是否可以通过变量接收此图像并将其绑定到HTML标签中?
所有问题都有将图像url映射到图像的解决方案,而我的问题是我必须在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变量中显示收到的图像?
答案 0 :(得分:1)
您可以在此博客文章中找到有关如何实现此目标的详细步骤-> https://blog.mikehodnick.com/angular-download-image-blob-and-bind-to-img/
TL; DR-它的长短之处在于您需要执行以下操作:
(请注意,这是使用 Angular 4.1.3 实现的)
service.ts
文件中的成员变量src
属性上面链接的博客文章中的示例代码:
视图
<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));
});
}
}
答案 1 :(得分:0)
在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">