首页 > 解决方案 > 我无法读取图像。它显示以下错误

问题描述

这是我的 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.jsangular

解决方案


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

onImageUpload(event)

这是因为打字稿。

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

如果可能的话,我建议使用 option1。


推荐阅读