我试图创建的棱角2/4服务,有可能上传文件。我找不到任何资源的解决办法,所以我可能想问你们。所以我们的想法是在组件中有一个带有type=file的输入字段。它有指令(change)="uploadFile($event)“。在组件.ts文件中:
uploadFile(event) {
this.images.push(this.uploadImgService.uploadImage(event));
}UploadImgService看起来是这样的:
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;
}因此,我理解操作正在进行异步,但我不知道如何以等待img加载的方式包装它。我认为这是由于缺乏技能所致:(当我将这些代码发布到组件中时,它肯定可以工作,但我的想法是提供服务。而且,我只是个角质初学者。所以,如果有更好的方法来重新调整这个想法,我很高兴收到你的来信。谢谢!
发布于 2017-11-01 20:28:27
你应该返回这样一个可以观察到的:
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();
};
});
} 在组件中,订阅可观察到的内容:
this.service.uploadImage(event).subscribe((img) => {
// Do what you want with the image here
});https://stackoverflow.com/questions/47062994
复制相似问题