简体   繁体   中英

Angular 7 Why Convert body to JSON string and to Object

Why do I have to convert event.body to JSON string and parse back to object?

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

If I directly pass, event.body to push , it doesn't compile:

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

If I pass event.body[0] , it compiles but it is an empty object {} .

The types are not compatible. Use the following code instead

const excelFile = event.body as ExcelFile;

That is because JSON.parse returns any as type so no Type error occurs. You need to define the type of event.body

let excelFile: ExcelFile = event.body as ExcelFile;

In that way you are saying to TS compiler "Hey, I know this data has this type"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM