如何从angular6 / 7中的帖子中获取大型json

问题描述

我已经迁移了一段代码,以便能够将数据作为excel文件以角度导出。 我假设json格式正确,并从服务器发送到有角度的一侧。我可以在浏览器的网络框架中看到它。 对于小型json,没关系,但是当json的大小开始变大时,答案仍然失败。 以下代码对应于服务调用

 exportSynthesis(recordId: number,moduleId: number) {
    const body = null;

    return this.http.post(this.apiUrl + `/data`
      + `${recordId}/module/${moduleId}`,body,{ 
        headers: new HttpHeaders({ 'Content-Type': 'application/json' }),observe: 'response',responseType: 'json' }).pipe(
        map((resp: any) => {
          return resp.body;
        }));
  }

这里是管理退货的方法

  exportSynthesis() {
    this.service.exportSynthesis(this.recordId,this.moduleId)
      .subscribe(
        (exportResult) => { this.exportResult = exportResult; },err => {
          console.log('err:',err);
          this.errorHandlerService.handleError('Failed',err);
          
        },() => {
          console.log('json:',this.exportResult);
          const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
          const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet },SheetNames: ['data'] };
          const excelBuffer: any = XLSX.write(workbook,{ bookType: 'xlsx',type: 'array' });

          const blob = new Blob([excelBuffer],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
          a.click();
          window.URL.revokeObjectURL(url);
          a.remove();
        });
  }

当前,我无法理解为什么它仍会错误地完成,并且控制台日志中仅显示“ ok”。 有想法吗?

致谢

解决方法

Angular的HttpClientModule默认响应是一个json。
您的问题是您尝试访问HTTP响应的body属性,但是当您尝试访问响应正文中的body属性时,Angular会对此进行解释。

从您的发布请求中删除observeresponseType并将响应视为json。应该可以。

,

找到:
只需要使用文本作为json

    return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
      + `${recordId}/module/${moduleId}`,body,{ 
        headers: headers,observe: 'response',responseType:  'text' as 'json'}).
          map((resp: any) => {
            return resp.body;      
          });
  }