Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser?

It's important to note that the app being referred to extends http to include a JWT in http requests. As mentioned on this link, extending http in this manner can lead to issues related to overriding RequestOptions.


THE DETAILS:

A backend API effectively serves the desired PDF when users enter

http://192.168.1.5:4000/whitepaper.pdf
in the web browser. However, the Angular application needs to programmatically access the white paper from the API and then display the PDF within the browser using a URL that is part of the Angular application.

The code snippet for the Angular application is shown below:

my.service.ts

getAll() {
    console.log('Inside getAll!');
    return this.http.get('http://192.168.1.5:4000/whitepaper.pdf').map((response: Response) => response.blob())
            .catch((err:Response) => {
        console.log('Error block!');
        return Observable.throw('error!');
     });;
}  

my.component.ts

getPDF() {
    console.log('Hey there, Jackass!');
    console.log(JSON.parse(localStorage.getItem('currentUser')).token);
    let myblob = new Blob([this.pDFService.getAll()], { type: 'application/pdf' });
    console.log(myblob.type);
    console.log(myblob.size);
    var fileURL = URL.createObjectURL(myblob);
    window.open(fileURL); // if you want to open it in new tab
}  

myblob.type displays as application/pdf, while myblob.size shows 15.

The backend API is built with Node.js/Express.

The Angular code example is retrieved from this answer, but it does not function correctly in the present scenario.

The code for custom-http.ts can be found at this link. The provided link mentions potential complications that may arise when http is overridden as seen in the current application.

Answer №1

When you call getAll(), it will return an Observable. Therefore, you can do the following:

    this.pDFService.getAll().subscribe( data => {
        let myblob = new Blob([data], { type: 'application/pdf' });
        var fileURL = URL.createObjectURL(myblob);
        window.open(fileURL); // open in a new tab
    })

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

Tips for receiving an array input in a GraphQL resolver

My query variables contain an array of strings that I need to use as the ids parameter inside my resolver. Below is the relevant code snippet. People.resolver.ts import { Resolver, Query, Mutation, Args, } from '@nestjs/graphql'; import { Peopl ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

What is the best way to maintain the order of variadic types for conditionally inferred conditional types?

Here is the type definition that I am working with: type Inner<Type> = Type extends Wrapper<infer U>[] ? U[] : never; Additionally, I have a function with the following signature: function myFunc<From extends Wrapper[], To>( values: ...

Is there a way to validate user input in the front-end using my ANTLR grammar implemented in the back-end?

I have implemented a system using the ANTLR parser in Java for the backend of our software (frontend in Angular 2+). While the connection between the frontend inputs and backend logic is working well, there is a concern that users may input data with typos ...

Tips for sorting through aggregated information in Foundry Functions

How can I filter on grouped data in Foundry Functions after grouping and aggregating my data? See the code snippet below for reference: @Function() public async grouping(lowerBound : Integer ): Promise<TwoDimensionalAggregation<string>> { ...

Having trouble integrating a Bootstrap-based ecommerce theme into an Angular8 project?

I have a bootstrap-based ecommerce theme with all the necessary files. The HTML theme is loading perfectly. Check out the official theme page I am integrating into my angular8 project: Theme Page Link I have created a repository for my angular8 project ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

The property 'x' cannot be found on the data type 'true | Point'

I am dealing with a variable named ctx which can be either of type boolean or Point. Here is how Point is defined: type Point = { x: number y: number } In my React component, I have the following setup: const App = () => { const [ctx, toggleC ...

Retrieve the value of a hidden input when a button is clicked using reactive forms in Angular

I am currently attempting to retrieve the values of hidden input fields that are dynamically added when the user clicks on the "insert more" button. If you'd like to view the code in action, you can visit this StackBlitz link: get hidden input value ...

The proper method for specifying contextType in NexusJS when integrating with NextJS

I am currently facing a challenge while trying to integrate Prisma and Nexus into NextJS. The issue arises when I attempt to define the contextType in the GraphQL schema. Here is how I have defined the schema: export const schema = makeSchema({ types: [ ...

"Encountering an issue with mounting components in React Unit Testing with Jest and Typescript

Having developed a simple app with components, here is the code: import GraphicCanvas from './Graphing/GraphCanvas'; import { drawCircle } from './Graphing/DrawCircle'; function App() { return ( <div className="App"&g ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

Issue with migrating TypeOrm due to raw SQL statement

Is it possible to use a regular INSERT INTO statement with TypeOrm? I've tried various ways of formatting the string and quotes, but I'm running out of patience. await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Running a function before triggering a refresh in Angular 2/4

When a user clicks or presses the F5 button on an HTML page, the page refreshes. However, before the refresh occurs, I want to execute a function or display a simple alert. The user can trigger a refresh by clicking the refresh button, pressing F5, or usi ...

An HTML table featuring rows of input boxes that collapse when the default value is not filled in

My table is populated with dynamic rows of input boxes, some of which may have a default value while others return an empty string ''. This causes the table to collapse on those inputs. <tr *ngFor="let d of displayData"> < ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

Generate a pre-signed URL for an AWS S3 bucket object using Typescript in NextJS, allowing for easy file downloads on the client-side using @aws-sdk/S3Client

In the utilization of v3 of the S3Client, it appears that all existing examples are based on the old aws-sdk package. The goal is for the client (browser) to access a file from S3 without revealing the key from the backend. From my research, it seems tha ...

Tips for incorporating ngSwitch into loops

How can I customize the index of the square dots and utilize ngSwitch to link the .form-style div with a list of questions and inputs? The goal is to toggle the visibility of each question by switching between the square dots. Currently, only one question ...

Writing TypeScript, Vue, and playing around with experimental decorators

After creating a Vue project through Vue-CLI v3.0.0-beta.15, the project runs smoothly when using npm run serve. However, TypeScript displays an error message stating that support for decorators is experimental and subject to change in a future release, bu ...