HttpResponse Blob

问题描述 投票:0回答:1

我有一个 Angular 13 的应用程序,我在其中向后面发出 POST 请求,我需要获取标头,并获取文件名来自的 Content-Disposition 部分。

因此,我创建了如下服务:

downloadRelatorioArquivos(data: any): Observable<HttpResponse<Blob>> {
     return this.http.post<HttpResponse<Blob>>(`${this.API}/baixarExcel`, { ...data }, { responseType: 'blob' as 'json'});
}

在我的组件中,我按如下方式调用该服务:

 onDownloadRelatorioArquivos() {
    this.loading = true;

    this.service.downloadRelatorioArquivos(this.form.value).subscribe({
      next: (res: HttpResponse<Blob>) => {
        console.log('dados responde blob');
        console.log(res.headers);
        this.loading = false;
        this.download(res, `RELATÓRIO_ARQUIVOS${this.form.value.data}.xlsx`);
      },
      error: () => this.loading = false
    });
  }

  private download(response: any, nomenclatura: string){
    const a = document.createElement('a');
    a.download = nomenclatura;
    a.href = window.URL.createObjectURL(response);
    a.click();
  }

但是,当执行 console.log(res.headers) 时,它出现未定义,因为 res 已经只带来了文件供下载。

angular download httpresponse
1个回答
0
投票

您应该添加

{ observe: 'response' }
以获得完整的 HTTP 响应。

您的服务方法应该是这样的:

downloadRelatorioArquivos(data: any): Observable<HttpResponse<Blob>> {
  return this.http.post<HttpResponse<Blob>>(
    `${this.API}/baixarExcel`,
    { ...data },
    { responseType: 'blob' as 'json', observe: 'response' }
  );
}

还要更改调用 download() 的方式:

this.download(res.body,`RELATÓRIO_ARQUIVOS${this.form.value.data}.xlsx`);
© www.soinside.com 2019 - 2024. All rights reserved.