简体   繁体   中英

Open pdf file in new tab in Angular

I'm trying to implement pdf file opening in new tab in Angular 9. I receive the file from api as a blob. But since window.URL.createObjectURL(blob); is deprecated I'm getting this Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided. error. I saw that now I should use MediaStream() for his kind of operations, but I can't figure it out how to make it work with blob.

My code now looks like this but it lacks the main part:

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'});
  }

Made my own solution from couple of answers. If I'm doing something wrong please correct me in the comments.

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM