【问题标题】:Open pdf file in new tab in Angular在 Angular 的新选项卡中打开 pdf 文件
【发布时间】:2020-10-09 13:38:08
【问题描述】:

我正在尝试在 Angular 9 的新选项卡中打开 pdf 文件。我从 api 接收文件作为 blob。但是由于 window.URL.createObjectURL(blob); 已被弃用,我收到了这个 Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided. 错误。我看到现在我应该使用MediaStream() 进行他的操作,但我不知道如何使它与 blob 一起使用。

我的代码现在看起来像这样,但它缺少主要部分:

downloadFile() {
    console.log('File download started.');
    const blob = this.agreementService.getPdfReport(this.agreementNumber);

    // Deprecated part
    const url = window.URL.createObjectURL(blob);
    const link = this.downloadZipLink.nativeElement;
    link.href = url;
    link.download = 'Agreement.pdf';
    link.click();
    window.URL.revokeObjectURL(url);
}

agreement.service.ts:

    getPdfReport(agreementNumber: string){
    this.requestUrl = `${configs.api}v1/reports/${agreementNumber}/Agreement.pdf`;
    let headers = new HttpHeaders();
    headers = headers.set('Accept', 'application/pdf');
    return this.http.get(this.requestUrl, {headers, responseType: 'blob'});
  }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    根据几个答案制作了我自己的解决方案。如果我做错了什么,请在 cmets 中纠正我。

    agreement.service.ts:

      getPdfReport(agreementNumber: string) {
        this.requestUrl = `${configs.api}v1/reports/${agreementNumber}/Agreement.pdf`;
        return this.http.get(this.requestUrl, { responseType: 'blob', observe: 'response'}).pipe(
          map((res: any) => {
            return new Blob([res.body], { type: 'application/pdf' });
          })
        );
      }
    

    agreement.component.ts:

    this.agreementService.getPdfReport(this.agreementNumber).subscribe(res => {
      const fileURL = URL.createObjectURL(res);
      window.open(fileURL, '_blank');
    });
    

    【讨论】:

    • 我正在尝试使用签名的网址。它得到了cors错误。有什么解决办法吗?
    猜你喜欢
    • 2021-12-02
    • 2019-04-12
    • 1970-01-01
    • 2018-01-23
    • 2018-11-28
    • 1970-01-01
    • 2017-08-06
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多