Как мне преобразовать reader.result в строку? - PullRequest
0 голосов
/ 09 июня 2019

Когда я пытаюсь загрузить изображение под углом три, возникает ошибка на 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);
        }

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>

1 Ответ

0 голосов
/ 09 июня 2019

Согласно официальной документации для FileReader.result () , тип возвращаемого значения для этого метода может быть string или ArrayBuffer.

Возможно, вам понадобится утверждение типа TypeScript , чтобы сообщить компилятору, что reader.result имеет тип string, поскольку вы установили тип для imagePreview как string.

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