簡體   English   中英

Angular 7為什么將主體轉換為JSON字符串和對象

[英]Angular 7 Why Convert body to JSON string and to Object

為什么我必須將event.body轉換為JSON字符串並解析回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);
      }      
    });

如果我直接將event.body傳遞給push ,它將無法編譯:

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 as類型,所以不會發生Type錯誤。 您需要定義event.body的類型

let excelFile: ExcelFile = event.body as ExcelFile;

這樣,您對TS編譯器說“嘿,我知道此數據具有此類型”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM