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!
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With