Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4 FileReader Service

I was trying to create Angular 2/4 Service with possibily to upload files. I could not find solution on any resourse so I probably wanna ask you guys. So the idea is somewhere in Component there is input field with type=file. It has directive (change)="uploadFile($event)". In component .ts file:

uploadFile(event) {
   this.images.push(this.uploadImgService.uploadImage(event));
}

UploadImgService looks this way:

private img: string;

uploadImage(e) {
  const file = e.target.files[0];
  const pattern = /image-*/;

  if (!file.type.match(pattern)) {
    alert('You are trying to upload not Image. Please choose image.');
    return;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    this.img = reader.result;
  };

  return this.img;
}

So, I understand that operation is going async, but I can't figure out how to wrap it the way it could wait until img is load. I think it is the result of skill lack:( When I post this code into component it surely works, but my idea is to make service. Also, I'm just a beginner in Angular. So, if there is a better way to reilize this idea I would be glad to hear from you. Thanks!

like image 914
Dmitriy Kavraiskyi Avatar asked Mar 08 '23 17:03

Dmitriy Kavraiskyi


1 Answers

You should return an observable like so:

uploadImage(e) {
  const file = e.target.files[0];
  const pattern = /image-*/;

  if (!file.type.match(pattern)) {
    alert('You are trying to upload not Image. Please choose image.');
    return;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return Observable.create(observer => {
    reader.onloadend = () => {
      observer.next(reader.result);
      observer.complete();
    };
  });
}  

And in the component, subscribe to the observable:

this.service.uploadImage(event).subscribe((img) => {
    // Do what you want with the image here
});
like image 104
user184994 Avatar answered Mar 20 '23 12:03

user184994