Angular2 - load binary image data asynchronously inside ngFor

I am trying to upload some images using the node fs module. I have work on a single image, but what is the right way to do this inside the ngFor loop?

I currently have:

<div *ngFor="let job of getJobs() | async"> <img src={{readImageFile(job.thumbUrl)}}> </div> 

getJobs () returns an observable from my service.

readImageFile () calls the server side method Meteor, which loads the image data using fs and returns it asynchronously:

  readImageFile(url) { if (url) { this.call('readImageFile', url, function(err, res) { if (err) { console.log(err); } else { console.log('read image file success'); return "data:image/jpg;base64," + res; } }); } } 

This does not work. So, what is the correct method for asynchronously loading data inside an ngFor loop?

Update

I tried using readImageFile(url) | async readImageFile(url) | async

 readImageFile: function(url) { var Future = Npm.require('fibers/future'); var myFuture = new Future(); fs.readFile(String(url), function read(error, result) { if(error){ myFuture.throw(error); } else { myFuture.return(new Buffer(result).toString('base64')); } }); return myFuture.wait(); } 
+2
source share
1 answer

This is not a good approach. readImageFile(job.thumbUrl) will be called with every change detection run, which is pretty common.

This should work

 <img [src]="readImageFile(job.thumbUrl) | async"> 

Pipe | async | async should prevent readImageFile() changes that causes readImageFile() .

Another approach would be to populate an array and bind it to this array

 getJobs() { this.jobs = /*code to get jobs*/.map(jobs => { this.images = new Array(jobs.length); jobs.forEach(item, idx => { readImageFile(idx, item.thumbUrl); }); return jobs; }); } 
  readImageFile(idx, url) { if (url) { this.call('readImageFile', url, (err, res) => { if (err) { console.log(err); } else { console.log('read image file success'); this.images[idx] = "data:image/jpg;base64," + res; } }); } } 
 <div *ngFor="let job of jobs | async; let idx=index"> <img [src]="images[idx]"> </div> 
+2
source

Source: https://habr.com/ru/post/1012182/


All Articles