[英]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實現的)
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));
});
}
}
在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.