Angular 7 为什么将正文转换为 JSON 字符串和对象
Angular 7 Why Convert body to JSON string and to Object
为什么我必须将 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.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
returnsany
是类型所以不会出现类型错误。您需要定义 event.body
的类型
let excelFile: ExcelFile = event.body as ExcelFile;
这样你就是在对 TS 编译器说 "Hey, I know this data has this type"
为什么我必须将 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.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
returnsany
是类型所以不会出现类型错误。您需要定义 event.body
let excelFile: ExcelFile = event.body as ExcelFile;
这样你就是在对 TS 编译器说 "Hey, I know this data has this type"