首页 > 解决方案 > base64 图像以角度显示 src 中的对象-对象?

问题描述

//Pipe code where we wil manage base64
import { HttpClient } from '@angular/common/http';
import { Pipe, PipeTransform } from '@angular/core';
import { ItemMaster } from '@cust-custap/core/http/item-master/item-master.service';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'getImageUrl',
})
export class GetImageUrlPipe implements PipeTransform {
  constructor(
      private httpClient: HttpClient,
      private itemMasterService :ItemMaster,
      public sanitizer:DomSanitizer ) {}

  transform(value: any, id: any): any {
      console.log(id);
      return this.itemMasterService.getItemImage(id).subscribe((data:any)=>{
        let img=this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,'+data);
        return img;
    });
  }
}
<!-- HTML part-->
<div *ngFor="let product_catalog  of result; let i= index;"> 
  <img class="card-img img-fluid" width="75" height="75" alt=""
     [src]="'' | getImageUrl: product_catalog.ID">
     </div>
在此处输入图像描述

我想在 html 中显示 base64 图像,我使用管道显示 base64 图像,管道也正常工作,但图像在控制台中显示对象-对象,我已经使用 this.sanitizer.bypassSecurityTrustResourceUrl 但它不工作。请检查下面我的代码,让我在这里做错了什么?

标签: angularbase64

解决方案


您看到[object object]是因为管道正在返回订阅,而不是 base64 字符串。

你需要在AsyncPipe这里使用。

您可以从管道的transform()方法中返回一个 observable,而不是返回订阅。

transform(value: any): Observable {
  return this.itemMasterService.getItemImage(value)
             .map(data => this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + data));
}

HTML部分可能是这样的

<div *ngFor="let product_catalog  of result; let i= index;"> 
  <img class="card-img img-fluid" width="75" height="75" alt=""
     [src]="product_catalog.ID | getImageUrl | async">
</div>

推荐阅读