How to have Angular open a PDF file in a new tab

Currently, I am working on implementing the functionality to open a PDF file in a new tab using Angular 9. The PDF file is received from an API as a blob. However, I have encountered an issue due to the deprecation of

window.URL.createObjectURL(blob);
. This has led to an error message stating
Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
. After researching, I discovered that I should now use MediaStream() for such operations, but I am struggling to understand how to make it work with a blob.

The current code snippet I have looks like this:

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

Answer №1

I combined various solutions to create my own approach. If there are any errors in my implementation, please provide feedback in the comments.

agreement.service.ts:

  requestPdf(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.requestPdf(this.agreementNumber).subscribe(res => {
  const fileURL = URL.createObjectURL(res);
  window.open(fileURL, '_blank');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

methods to ensure a preselected value remains in use within mat-select in the context of Angular

In my current project, I've incorporated a unique mat-select component. Here's the corresponding code: <div class="col-md-6"> <mat-form-field> <mat-select placeholder="Select Job" formControlName="job_instruc ...

Angular progress bar with intermittent breaks

Currently developing an Angular application and looking to implement a progress bar similar to the one displayed in the linked images. https://i.sstatic.net/5doDu.png https://i.sstatic.net/SP2it.png Although there are multiple progress bars available on ...

Is there a way to safeguard against accidental modifications to MatTab without prior authorization?

I need to delay the changing of the MatTab until a confirmation is provided. I am using MatDialog for this confirmation. The problem is that the tab switches before the user clicks "Yes" on the confirmation dialog. For instance, when I try to switch from ...

Vuex - Managing dependencies within nested modules

I am facing a challenge in expressing a dependency between properties within my app's state using Vuex. Upon logging in, the user must select one of several workspaces to connect to. It is essential for the workspace to depend on the login status; ho ...

Combine data from a new observable with the existing data in Angular using RxJS

I have a list stored as an observable[]. To subscribe to it in the template, I am using async. Each time I scroll, this method is called: onScroll() { this.list$ = this.list$?.pipe( tap((list) => { this.notificationService . ...

Steps to include a horizontal divider in the footer section of an angular-material table

Is it possible to add a line between the last row (Swimsuit) and the footer line (Total)? If so, how can I achieve this using Angular 15? https://i.stack.imgur.com/581Nf.png ...

Vue and TypeScript: The elusive 'exports' remains unidentified

Since switching my App.vue to utilize typescript, I am facing a compiler error: [tsl] ERROR in \src\main.ts(2,23) TS2304: Unable to locate the name 'exports'. If I have vue-serve recompile after making changes, I encounter t ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

On iOS devices, the confirm/cancel alert box in Ionic v3 does not display in the center as expected

Encountering an issue with Ionic v3 where the alert box appears at the top only when a text box is included within it. This behavior is observed on regular devices like iPhones, but functions correctly on Android devices. Other form elements like checkboxe ...

The specified starting point "@angular/material/card" cannot be accessed due to missing dependencies

When attempting to deploy a web application on Heroku, I encountered the following error message: - Generating browser application bundles (phase: setup)... Compiling @angular/core : es2015 as esm2015 Compiling @angular/common : es2015 as esm2015 Compiling ...

What is the best way to create a props interface that includes state and setState values that are being

As I dive deeper into TypeScript, a hurdle has appeared in my app. Upon introducing React.FunctionComponent to my components, an issue arose with my Props interface. The error message reads: Type '({ value, setValue, }: Props) => JSX.Element' ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

When using Observables in AngularFire2, the $ref property does not get captured

Recently, I started working with AngularFire2 (version 4.0.0-rc.1) and encountered a challenge that has me stuck: getWishlist$(): FirebaseListObservable<{}> { return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID) ...

What is the process for defining a series of tests for karma through code?

Currently, I am in the process of developing an Angular Test Explorer. The exciting part is that I can view all the tests and execute them collectively by leveraging the karma module as shown in this code snippet: public async runWithModule(): Promise&l ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

A guide on implementing JSON data projection with TypeScript

{ "ClaimType": ["The 'Claim Type' should have a minimum length of 4 characters. You have only entered 2 characters."], "ClaimValue": ["The 'Claim Value' should have a minimum length of 4 characters. You have only entered 1 chara ...

Do Angular pipe promises have the potential to disrupt an application's functionality?

Within my small library, I have implemented a translation pipe that functions perfectly when using Observables. The relevant code snippet can be found here: this.localizationChanges.subscribe(() => { this.fluentService .translationObservable ...

Steps for deploying an Angular 2 application without the need for a server

I am embarking on a basic Angular 2 project, however, I do not wish to manage it using npm. Is there any alternative method to initiate the project with the following steps: Compile all *.ts files Transfer compiled js-files to a separate directory (not ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...