Angular 7为什么将body转换为JSON字符串并转换为对象



为什么我必须将event.body转换为JSON字符串并解析为对象?

this.excelFileService.upload(this.currentFileUpload).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
        this.progress.percentage = Math.round(100 * event.loaded / event.total);
      } else if (event instanceof HttpResponse) {
        let excelFile: ExcelFile = JSON.parse(JSON.stringify(event.body));
        this.excelFiles.push(excelFile);
      }      
    });

如果我直接通过,event.bodypush,则不会编译:

ERROR in src/app/excel-file/excel-file.component.ts(54,30): error TS2345: Argument of type '{}' is not assignable to parameter of type 'ExcelFile'.
  Type '{}' is missing the following properties from type 'ExcelFile': filename, path, createdAt

如果我通过 event.body[0],它会编译,但它是一个空的对象{}

类型不兼容。改用以下代码

const excelFile = event.body as ExcelFile;

这是因为JSON.parse返回any作为类型,因此不会发生类型错误。您需要定义event.body

的类型
let excelFile: ExcelFile = event.body as ExcelFile;

以这种方式,您对TS编译器说:"嘿,我知道此数据具有此类型"

最新更新