Angular 2/4 FileReader服务

4

我正在尝试创建一个具有上传文件功能的Angular 2/4服务。我在任何资源中都找不到解决方案,所以我想问问你们。所以,在组件中,有一个类型为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;
}

我知道操作正在异步进行,但我不知道如何包装它以便等待图像加载。我认为这是技能不足的结果:( 当我将此代码发布到组件中时,它肯定会工作,但我的想法是创建服务。此外,我只是Angular的初学者。如果有更好的实现这个想法的方法,我很高兴听到您的建议。谢谢!

1个回答

8
您应该这样返回一个可观察对象:
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
});

哦,非常感谢!是的,这确实帮了我很多!另外,我想知道把这样的东西放在服务中是否正确?还有其他处理方法吗? - Dmitriy Kavraiskyi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接