【问题标题】:I am not able to read the image. It's showing the following error我无法阅读图像。它显示以下错误
【发布时间】:2021-12-04 03:57:59
【问题描述】:

这是我的 ng 代码:

<div class="p-field col-12">
   <label for="image">Main Image</label>
     <input type="file" class="p-inputtext" accept="image/*" (change)="onImageUpload($event)">
     <div>
       <img {src}="imageDisplay" alt="">
     </div>
</div>

这是我的组件代码:

export class ProductsFormComponent implements OnInit {
     
  imageDisplay: string | ArrayBuffer | null | undefined;
       
  constructor() { }
    
  ngOnInit(): void {}

  onImageUpload(event){
    const file = event.target.files[0];

    if (file) {
      const fileReader = new FileReader();
      
      fileReader.onload = () => {
            this.imageDisplay = fileReader.result;
      }

      fileReader.readAsDataURL(file);
    }
  }    
  }

  get productForm(){
    return this.form.controls;
  }
}

这是错误:

Error: apps/admin/src/app/pages/products/products-form/products-form.component.ts:77:17 - error TS7006: Parameter 'event' implicitly has an 'any' type.

77   onImageUpload(event)

【问题讨论】:

标签: node.js angular


【解决方案1】:

错误是由于您定义 onImageLoad 方法的方式造成的。

onImageUpload(event)

这是因为打字稿。

  1. 由于 Angular 使用 typescript,我们可以指定方法调用的参数类型。 示例:以下将解决错误
onImageUpload(event: Event)
  1. 有一个 tsconfig.json 由 Angular cli 自动生成的文件。此文件指定 typescript 编译器在编译代码时使用的配置。在这里我们可以配置我们在项目中需要的类型等。因此将noImplicitAny选项设置为false也可以解决问题。

如果可能的话,我会推荐使用 option1。

【讨论】:

  • 感谢您的回答。我也解决了我的问题。非常感谢?
【解决方案2】:

使用这个

const file: File = <File>event.target.files[0];

而不是

this.file = event.target.files[0];

然后

const reader = new FileReader();
reader.readAsDataURL(file);

试试这个就行了

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多