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
-
can you create a small example on stackblitz.com?alt255– alt2552020年05月11日 14:55:00 +00:00Commented May 11, 2020 at 14:55
-
But getting image from my company's ntnet server will not work.. It won't help...vijay sahu– vijay sahu2020年05月11日 15:06:10 +00:00Commented May 11, 2020 at 15:06
-
@vijaysahu you can use placeholder.com to get an imageJuan– Juan2020年05月11日 15:12:48 +00:00Commented May 11, 2020 at 15:12
-
I sure it will not help but again if you guys want then I will do it... My actual issue is how to bind when you are getting base64 image using subscriber in pipe...vijay sahu– vijay sahu2020年05月11日 15:20:22 +00:00Commented May 11, 2020 at 15:20
1 Answer 1
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
4 Comments
forkJoin([getCategories(),getPersons(),getInvoices()]).subscribe(([categories,persons,invoices])=>{...})