如何将 reader.result 转换为字符串?

Cha*_*hne 0 typescript angular angular-forms angular7

当我尝试在角度三上上传图像时,下面的打字稿文件中的 reader.result 出现错误,我该如何解决此问题?我console.log(image)在 onImagePicked 函数中添加了它,但它也没有显示在控制台中,为什么它不显示在控制台中?

打字稿文件

     imagePreview:string;


ngOnInit(){
  this.form = new FormGroup({
    title : new FormControl(null,{validators:[Validators.required]}),
    content: new FormControl(null,{validators:[Validators.required]} ),
    image: new FormControl(null, {validators: [Validators.required]})
  });


        onImagePicked(event: Event){
          const file = (event.target as HTMLInputElement).files[0];
          this.form.patchValue({image: file});
          this.form.get('image').updateValueAndValidity();
          console.log(file);
          const reader = new FileReader();
          reader.onload = () => {
            this.imagePreview = reader.result;
          };
          reader.readAsDataURL(file);
        }
Run Code Online (Sandbox Code Playgroud)

网页文件

<mat-card>
  <mat-spinner *ngIf="isLoading"></mat-spinner>
  <form [formGroup]="form" (submit)="onAddPost()"  *ngIf="!isLoading">
    <mat-form-field>
      <input matInput type="text" formControlName="title" placeholder="title"  >
      <mat-error *ngIf="form.get('title').invalid" >Please enter the Title</mat-error>
    </mat-form-field>

    <mat-form-field>
      <textarea matInput rows="6" formControlName="content" placeholder="caption"   ></textarea>
      <mat-error *ngIf="form.get('content').invalid" >Please enter the Content</mat-error>
    </mat-form-field>
<div class='image-preview'>
  <img src="" [alt]="form.value.title">
</div>


    <div>
        <button mat-stroked-button type="button" (click)="filePicker.click()">Add Image</button>
        <input type="file" #filePicker (chnage)="onImagePicked($event)">
      </div>

    <button  mat-raised-button color="accent" type="submit">Save Post</button>
</form>
</mat-card>
Run Code Online (Sandbox Code Playgroud)

wen*_*jun 7

根据FileReader.result()的官方文档,该方法的返回值的类型可能是 of string、 或ArrayBuffer

您可能需要使用 TypeScript 的类型断言来告诉编译器其reader.result类型为string,因为您已将类型设置为imagePreviewas string

reader.onload = () => {
  this.imagePreview = reader.result as string;
};
Run Code Online (Sandbox Code Playgroud)