【问题标题】:How to bind image into src attribute using Angular 8如何使用 Angular 8 将图像绑定到 src 属性
【发布时间】:2020-08-27 03:28:18
【问题描述】:

我需要在 UI 上绑定员工列表,这已经使用 *ngFor 完成。

现在,我想使用管道为每个员工绑定图像。 在每个员工的管道中,我必须访问服务器才能获取图像(它以 Base64 格式返回)。

问题: 当我尝试使用 subscriber 获取图像时,它不起作用。

this.userSerivce.GetProfileImage(ntnet).subscribe(img => {
      if (img !== '' && img !== undefined && img.length > 64) {
        return prefix + img;
      } else {
        return profileImage;
      }
    });

src 属性的 UI 上我可以看到这个

src=(unknown)    

注意:

如果从 API 获取所有图像以及员工自身,则由于图像处理(从 ntnet 获取 img),响应会变得非常慢。

有没有其他最好的方法在UI上绑定动态图像而不冻结UI

【问题讨论】:

  • 你能在 stackblitz.com 上创建一个小例子吗?
  • 但是从我公司的 ntnet 服务器获取图像不起作用.. 它没有帮助...
  • @vijaysahu 您可以使用placeholder.com 获取图像
  • 我确定这无济于事,但如果你们愿意,我会再次这样做...我的实际问题是当您使用管道中的订阅者获取 base64 图像时如何绑定...跨度>

标签: angular data-binding angular8


【解决方案1】:

我会尝试有一个对象数组。首先你得到用户,在使用 forkJoin 得到所有图像之后。拥有所有图像后,将值分配给属性“img”。

好吧,当你收到一个base64的图像时,你需要使用DomSatinize,所以在你的构造函数中

constructor(private sanitizer:DomSanitizer) {}

想象你有

persons=[
{id:1,name:"Person 1",img:null},
{id:2,name:"Person 2",img:null}
...
]
//you create an array of observables
//and subscribe to forkJoin
forkJoin(this.persons.map(p=>this.userSerivce.GetProfileImage(p.id)))
.subscribe((res:any[])=>{
   //in res[0] you has the image of the first call
   //in res[1] you has the image of the second call
   //....
   res.forEach((img,index)=>{
     this.persons[index].img=
         this.sanitizer.bypassSecurityTrustUrl("data:image/png;base64," + img) 
   })
 })

你有一个类似的 .html

<div *ngFor="let person of persons">
   <img *ngIf="person.img" [src]="person.img"/>{{person.name}}
</div>

注意:我想你收到了一些类似的东西:

iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDI...

查看stackblitz中的示例

注意 2:在 stackblitz 中,我将 this.userService.GetProfileImage 替换为一个简单的 getImagen

【讨论】:

  • 完美答案...只有一个问题,一旦每个 emp 出现 img,我们不能根据它们的 EmpId 而不是使用索引将这些 img 映射到每个 emp。
  • 我不太了解。你有两个数组,一个是人物,一个是图像。当我们将人员数组映射到 Observables 数组并使用 forkJoin 时,图像数组是有序的,res[0] 是对 getImagen(persons[0].id) 的响应,res[1] 是对 getImagen(persons[0].id) 的响应getImagen(persons[1].id)... 您可以将 res[index] 与 people[index] 联系起来
  • 明白你的意思,我只是有点担心 EmpId 及其图像的顺序/顺序.. 意味着它最终不应该不匹配......
  • Vijay,图像可以在不同时间加载且无序,但只有当 all 图像已加载时,forkjoin “完成”并给我们响应(当然订购)。认为有时您使用 forJoin 来获得不同的答案,例如在 dbs 中通常使用 forkJoin 来获取首字母表 - 并使用“destructuring-”,有些像 forkJoin([getCategories(),getPersons(),getInvoices()]).subscribe(([categories,persons,invoices])=&gt;{...})
猜你喜欢
  • 2021-07-23
  • 2015-06-18
  • 2018-03-27
  • 2016-10-21
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2019-07-09
  • 2019-03-07
相关资源
最近更新 更多