【问题标题】:Type 'ArrayBuffer' is not assignable to type 'string'类型“ArrayBuffer”不可分配给类型“字符串”
【发布时间】:2018-12-12 20:47:11
【问题描述】:

使用angular6和node.js的应用程序遇到了一个问题,现在正在写服务器上负责上传图片的部分,创建了imagePreview = ""变量(是的,默认为空)

ERROR in src/app/categories-page/categories-form/categories-form.component.ts(74,7): error TS2322: Type 'string | ArrayBuffer' is not assignable to type 'string'. [1] Type 'ArrayBuffer' is not assignable to type 'string'.

这是我在第74行的,我不明白错误在哪里(WebStorm强调reader.result)

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

请告诉我如何解决

负责下载图片的组件代码:

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {CategoriesService} from "../../shared/services/categories.service";
import {switchMap} from "rxjs/operators";
import {of} from "rxjs";
import {MaterialService} from "../../shared/classes/material.service";
import {Category} from "../../shared/interfaces";

@Component({
  selector: 'app-categories-form',
  templateUrl: './categories-form.component.html',
  styleUrls: ['./categories-form.component.css']
})
export class CategoriesFormComponent implements OnInit {

  @ViewChild('input') inputRef: ElementRef
  form: FormGroup
  image: File
  imagePreview=''
  isNew= true
  category: Category

  constructor(private route: ActivatedRoute,
              private categoriesService: CategoriesService) { }

  ngOnInit() {
    this.form=new FormGroup({
      name:new FormControl(null, Validators.required)
    })

    this.form.disable()

    this.route.params
      .pipe(
        switchMap(
          (params: Params)=>{
            if(params['id']){
              this.isNew=false
              return this.categoriesService.getById(params['id'])
            }
            return of (null)
          }
        )
      )
      .subscribe(
        (category: Category)=>{
          if(category){
            this.category = category
            this.form.patchValue({
              name: category.name
            })
            this.imagePreview=category.imageSrc
            MaterialService.updateTextInputs()
          }

          this.form.enable()
        },
        error=>MaterialService.toast(error.error.message)
      )
  }

  triggerClick(){
    this.inputRef.nativeElement.click()
  }

  onFileUpload(event: any){
    const file = event.target.files[0]
    this.image = file

    const reader = new FileReader()

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

    reader.readAsDataURL(file)
  }

  onSubmit(){

    let obs$

    this.form.disable()

    if(this.isNew){
      obs$ = this.categoriesService.create(this.form.value.name, this.image)
    } else {
      obs$ = this.categoriesService.update(this.category._id, this.form.value.name, this.image)
    }

    obs$.subscribe(
      category =>{
        this.category = category
        MaterialService.toast('Изменения сохранены!')
        this.form.enable()
      },

      error=>{
        MaterialService.toast(error.error.message)
        this.form.enable()
      }
    )
  }
}

创建和编辑

create(name: string, image?:File) : Observable<Category>{
    const fd = new FormData()

    if(image){
      fd.append('image', image.name)
    }

    fd.append('name', name)
    return this.http.post<Category>('/api/category', fd)
  }

  update(id: string, name: string, image?:File) : Observable<Category>{

    const fd= new FormData()
    if(image){
      fd.append('image', image.name)
    }
    fd.append('name', name)
    return this.http.patch<Category>(`/api/category/${id}`, fd)
  }

【问题讨论】:

  • 好吧,reader.result 是 string | ArrayBuffer,this.imagePreview 是 string。您没有提供足够的信息让任何人知道reader 是什么。如果它是 ReadbleStream 或类似的,请确保它已完成阅读并将其转储为字符串或强制其键入字符串:reader.result as string
  • @joh04667 我现在改了一点,现在行的形式是this.imagePreview = reader.result as string 是的,现在它没有报错,但问题是它传输的变量imagePreview 是空的,并且必须传输图片链接
  • 听起来它仍然是ArrayBuffer,因此是元组类型。你需要先解码
  • @joh04667 有这个困难,我刚开始研究,我现在尝试更新问题并添加负责下载图片的代码

标签: javascript angular angular6


【解决方案1】:

ArrayBuffer 作为字符串可能会导致数据截断(必须测试)。
所以你必须明确地转换它,以告诉编译器“我知道我在做什么”。

试试这个,它对我有用:

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

【讨论】:

    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2022-06-25
    • 2021-02-22
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多