![](/img/trans.png)
[英]convert JSON format string array into real JSON array object in Angular
[英]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.