Reputation: 815
I have a requirement to bind a list of employee on UI, which is already done using *ngFor.
Now, I wanted to bind image for each employee using pipe. In pipe for every employee I have to hit the server to get the Image(it returns in Base64 format).
Problem: It's not working when I am try to get the image using subscriber.
this.userSerivce.GetProfileImage(ntnet).subscribe(img => {
if (img !== '' && img !== undefined && img.length > 64) {
return prefix + img;
} else {
return profileImage;
}
});
And on UI in src attribute I can see this
src=(unknown)
Note:
If getting all images along with employee it self from API then the response become very slow due to image processing (getting img from ntnet).
Is there any other best way to bind dynamic images on UI without freezing the UI
Upvotes: 0
Views: 1590
Reputation: 57929
I'll try has an array of object. At first you get the users, after get all the images using forkJoin. When you has all the images, you asign the value to the property "img".
Well, when you received a imagen in base64, you need use DomSatinize, so in your constructor
constructor(private sanitizer:DomSanitizer) {}
Imagine you has
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)
})
})
you has an .html like
<div *ngFor="let person of persons">
<img *ngIf="person.img" [src]="person.img"/>{{person.name}}
</div>
NOTE: I imagine you received some like:
iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDI...
see an example in stackblitz
NOTE2: In the stackblitz I replace the this.userService.GetProfileImage by a simple getImagen
Upvotes: 1