【问题标题】:Angular 7 Why Convert body to JSON string and to ObjectAngular 7 为什么将正文转换为 JSON 字符串和对象
【发布时间】:2019-07-08 06:56:51
【问题描述】:

为什么我必须将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],它会编译但它是一个空对象{}

【问题讨论】:

    标签: javascript angular typescript httpresponse angular7


    【解决方案1】:

    类型不兼容。请改用以下代码

    const excelFile = event.body as ExcelFile;
    

    【讨论】:

      【解决方案2】:

      这是因为JSON.parse 返回any 作为类型,所以不会发生类型错误。你需要定义event.body的类型

      let excelFile: ExcelFile = event.body as ExcelFile;
      

      这样你对 TS 编译器说“嘿,我知道这个数据有这种类型”

      【讨论】:

      • 非常感谢。
      猜你喜欢
      • 2019-08-27
      • 2020-05-27
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2011-04-23
      • 2012-06-14
      • 2012-02-20
      • 2015-01-03
      相关资源
      最近更新 更多