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

时间:2019-06-09 06:43:00

标签: angular typescript angular7 angular-forms

当我尝试在角度3上载图像时,reader.result出现错误,下面是打字稿文件,我该如何解决? 我在onImagePicked函数中添加了console.log(image),但它也未在控制台中显示?

打字稿文件

     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);
        }

HTML文件

<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>

2 个答案:

答案 0 :(得分:0)

根据FileReader.result()的官方文档,该方法的返回值类型可能为stringArrayBuffer

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

reader.onload = () => {
  this.imagePreview = reader.result as string;
};

答案 1 :(得分:0)

声明时,您也可以将imagePreview的类型设置为imagePreview: string | ArrayBuffer

或者您也可以这样做:

reader.onload = () => {
      this.imagePreview = <string>reader.result;
    }