[英]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? 为什么我必须将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);
}
});
If I directly pass, event.body
to push
, it doesn't compile: 如果我直接将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
If I pass event.body[0]
, it compiles but it is an empty object {}
. 如果我通过event.body[0]
,它将编译但它是一个空对象{}
。
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. 那是因为JSON.parse
返回any
as类型,所以不会发生Type错误。 You need to define the type of event.body
您需要定义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" 这样,您对TS编译器说“嘿,我知道此数据具有此类型”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.