如何使用Angular 8将图像绑定到src属性

如何使用Angular 8将图像绑定到src属性,angular,data-binding,angular8,Angular,Data Binding,Angular8,我需要在UI上绑定员工列表,这已经使用*ngFor完成 this.userSerivce.GetProfileImage(ntnet).subscribe(img => { if (img !== '' && img !== undefined && img.length > 64) { return prefix + img; } else { return profileImage;

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

this.userSerivce.GetProfileImage(ntnet).subscribe(img => {
      if (img !== '' && img !== undefined && img.length > 64) {
        return prefix + img;
      } else {
        return profileImage;
      }
    });
现在,我想为每个使用管道的员工绑定图像。 在管道中,对于每个员工,我必须点击服务器才能获取图像(它以Base64格式返回)

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

this.userSerivce.GetProfileImage(ntnet).subscribe(img => {
      if (img !== '' && img !== undefined && img.length > 64) {
        return prefix + img;
      } else {
        return profileImage;
      }
    });
src属性的UI上,我可以看到这一点

src=(unknown)    
注意:

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


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

我将尝试使用对象数组。在使用forkJoin获取所有图像之后,首先获取用户。当您拥有所有图像时,您将该值指定给属性“img”

当您在base64中收到一个imagen时,您需要使用,所以在构造函数中

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>
请参见中的示例


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

您能在stackblitz.com上创建一个小示例吗?但是从我公司的ntnet服务器获取图像将不起作用。。这不会有帮助的…@vijaysahu你可以用它来获得一张图片我肯定不会有帮助,但如果你们想的话,我会做的。。。我的实际问题是,当您使用管道中的订阅服务器获取base64映像时,如何绑定…完美答案。。。只有一个问题,一旦每个emp都出现了img,我们就不能根据它们的EmpId而不是使用索引将这些img映射到每个emp。我不太明白。您有两个数组,一个包含人物,一个包含图像。当我们将Person数组映射到Observable数组并使用forkJoin时,图像数组是有序的,res[0]是对getImagen的响应(persons[0].id),res[1]是对getImagen的响应(persons[1].id)。。。你可以把res[index]和persons[index]联系起来。明白你的意思了,我只是有点担心EmpId和他们的图像的顺序。。意味着最终它不应该不匹配…Vijay,图像可以在不同的时间无序加载,但只有在所有图像加载后,forkjoin才会“finalize”并给出响应(当然是有序的)。设想一下,有时您使用forJoin来获得不同的答案,例如,在dbs中,使用forkJoin来获取初始值表,并使用“destructuring”,例如
forkJoin([getCategories(),getPersons(),getInvoices()])。subscribe([categories,persons,invoices])=>{…}