【问题标题】:How to access Response Headers in the get api call - Angular 7如何在 get api 调用中访问响应标头 - Angular 7
【发布时间】:2020-02-14 19:19:25
【问题描述】:

我正在尝试从后端下载具有特定文件名的 .csv 文件。如何使用 Angular 7 从 api 响应标头访问文件名

我的服务(api 调用):

 public getDownloadFile(masterDistributorId: number, runDate: string) {
    return this.http.get
      (`${environment.apiUrl}command-center/report/download/? 
         masterDistributorId=${masterDistributorId}&runDate=${runDate}`, {
        headers: new HttpHeaders().append('Content-Type', 'application/csv'),
        responseType: 'blob',
        observe: 'response'
      }
      );
  }

我的订阅电话:

 public Download(row: DistributorItem) {
    console.log(row.masterDistributorId);
    console.log(this.RunDate);
    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      console.log(res.headers);
      this.SaveFile(res);
    });
  }

【问题讨论】:

  • showConfigResponse() { this.configService.getConfigResponse() // resp 的类型为 HttpResponse<Config> .subscribe(resp => { // 显示其标题 const keys = resp.headers.keys() ; this.headers = keys.map(key => ${key}: ${resp.headers.get(key)}); // 直接访问body,类型为Config.this.config = { ... resp.body }; }); } 访问angular.io/guide/http了解更多详情。

标签: angular


【解决方案1】:

获取响应头值:Reading the full response

key = 'content-disposition';
contentDisposition = response.headers.get(key)

拆分头内容配置字符串:String.prototype.split()

filename = contentDisposition.split("=")[1];

你的情况:

    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      let filename = res.headers.get('content-disposition').split("=")[1];
      console.log(filename);
      this.SaveFile(res);
    });

【讨论】:

  • 虽然此代码可能会解决问题,但 including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
  • 尝试使用这个键'Content-Disposition'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多