【问题标题】:failed to download file in angular 5无法以 Angular 5 下载文件
【发布时间】:2018-10-06 04:33:50
【问题描述】:

我正在尝试从角度 5 中的 url 下载 pdf 文件。通过将 url 和“下载”属性添加到“a”标签,它在 html 中运行良好。当我尝试在角度 5 中执行相同操作时,但是它不工作。

service.ts

pdfDownload() {
         var options = new RequestOptions({responseType: ResponseContentType.Blob });

        // Process the file downloaded
        return this.http.get('https://.....test.pdf', options);
    }

component.ts

this.rcycCommonService.pdfDownload().subscribe((res)=>{
        this.saveFile(res.blob());
    })
saveFile (blobContent)  {
        var blob = new Blob([blobContent], { type: 'application/pdf' });
        saveAs(blob,"mypdf.pdf");
    };

但它显示以下错误。

ERROR in src/app/rcyc-services/rcyc-common/rcyc-common.service.ts(426,137): error TS2345: Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'headers' are incompatible.
    Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
      Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
        Index signature is missing in type 'Headers'.

任何人都可以发布正确的代码以下载 angular 5 中的文件吗?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我仍然无法从 url 创建 blob 对象

标签: angular5


【解决方案1】:

这是一个 Typescript 编译错误。正如错误所说,this.http.get 的第二个参数应该是Headers、HttpHeaders 或字符串索引对象(不是RequestOptions)。

【讨论】:

  • 你能在 Angular 5 中发布一个工作代码吗?我花了很多时间
  • 您使用什么 IDE?您是否在 http.get 调用中获得语法高亮显示?在您尝试运行它之前,您应该会看到一个错误。
  • 是的,我在 http.get 中得到了语法高亮
  • 语法高亮是否告诉你为什么它不能编译?查看 Angular 文档,了解应该传递哪些参数 HttpClient.get。
【解决方案2】:

你可以使用 axios 来下载文件

你可以安装axios

npm i axios

并在您的服务中导入

import axios from 'axios';

return axios.get(`${URL}`,{headers , responseType:"blob"}).then(({ data }) => {
      const downloadUrl = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', `${fileName}.csv`); //any other extension and type you want
      document.body.appendChild(link);
      link.click();
      link.remove();
    });

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2019-03-28
    • 2018-08-12
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多