簡體   English   中英

在角度6中綁定服務中的圖像

[英]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實現的)

  1. 使用http獲取圖像
  2. 將響應類型設置為BLOB,以便我們以二進制格式獲取圖像
  3. 消毒斑點反應
  4. 將已清理的響應分配給service.ts文件中的成員變量
  5. 將成員變量分配給HTML視圖中的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));
      });
  }

}

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM