Utilizing the Embed tag to invoke URL requests repeatedly within an Angular application

I am currently developing a custom PDF viewer to display the PDF content fetched from an API response. The main issue I'm encountering is that the API call is being triggered multiple times, approximately 50 - 60 times or even more in some cases. Strangely, this excessive API calling only occurs when trying to display the PDF document. If I include a link to any external website, the API is called just once. Furthermore, this problem persists whether I use an iframe or embed element. Despite implementing two different solutions, both seem to trigger the API multiple times but with varying status codes.

The complete file path is retrieved from an API endpoint structured as follows:

http://localhost:4200/upload/training/getMedia?path=<FULL PATH TO PDF>
. A JAVA server generates the BLOB and sends it back as a response.

Attempted Solution 1:

sanitizeURL(URL: string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(encodeURIComponent(URL));
}

However, this approach results in an 'Unsafe URL' error as depicted below -

https://i.sstatic.net/kmFUg.png

Attempted Solution 2:

Referenced from Angular 2 how to display .pdf file, where using ng2-pdf-viewer proved ineffective due to a registration error for pdf-viewer module.

async sanitizeURL(url: string) {
  try {
    const BLOB = await this.fetchTraining.getMedia(url).toPromise();
    const sanitize = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(new Blob([BLOB], {type:'application/pdf'})));
    return this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, sanitize);
  } catch(error) { console.log(error) }
}

Adopting this method leads to repeated API calls, similar to the previous solution, causing inefficiencies as shown here -

https://i.sstatic.net/p3hfN.png

In both scenarios, the HTML markup remains consistent as seen below:

<div *ngIf="condition_true">
    <embed [attr.src]="sanitizeURL(url+list.path)" width="500" height="375" type="application/pdf">
</div>

In addition to these attempts, I also experimented by directly passing the URL within the src attribute like so -

<div *ngIf="condition_true">
    <embed [attr.src]="url+list.path" width="500" height="375" type="application/pdf">
</div>

This resulted in a recurrence of the Solution 2 error, but interestingly, only occurred once.

Any suggestions on resolving this issue? I am utilizing Angular 8 for development purposes.

Answer №1

Instead of recreating the source URL every time the template is updated, it's advised to set it as a component property. Here's an example:

@Component({
    template: `<embed attr.src="{{this.url}}" width="500" height="375" type="application/pdf">`
})
export class MyCoolComponent {
    constructor(){
        this.url = this.sanitizeUrl(URL)
    }

    sanitizeUrl(url: string){
        return this.sanitizer.bypassSecurityTrustResourceUrl(encodeURIComponent(URL));
    }
}

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

There was an issue loading the map on an HTML code that was returned from an ajax request

I'm currently working on building my own personal website, which is also my first webpage, and I'm encountering some difficulties with displaying a Google map. Here's a breakdown of my situation: my webpage consists of four links that load ...

Exploring the use of ngResource in conjunction with HttpBackend - Potentially unreached rejection issue

Issue Currently, I am working on testing a controller utilizing Karma, Mocha, Chai, and PhantomJS as part of the testing process. IndexCtrl.js (simplified) app.controller('IndexCtrl', ['$scope', '$resource', function($scope ...

React with Typescript: Potential occurrence of an undefined object

While working with React and TypeScript, I encountered the error Object is possibly 'undefined' when using language.toLowerCase().includes(selectedCategory). To address this issue, I implemented a check as shown below. Although this resolved th ...

How to dynamically append a new array to an existing array of objects in React JS

When the button is clicked, I am retrieving the ID and quantity values. My goal is to add a new array inside the object array. See the code snippet below: addData = (d,v) => { const product = []; for (let i = 0; i < 1; i++) { produ ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

The ngOnInit child function fails to activate when trying to assign a fresh object

On the parent page, I am passing user data to a child component in this way: <ng-container *ngIf="leaderboard"> <app-leaderboard-preview [user]="user" (click)="goToLeaderboard()"></app-leaderboard-preview> </ng-container> In t ...

How can I resolve the Vue warning about an unknown custom element <password-input>?

I've been working on resolving an error within a component, but unfortunately, I'm still encountering issues. The error message is as follows: [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive co ...

Using cookies for authentication in Angular 5

Currently, I am in the process of building a website with Angular 5 and Express JS. One issue I am facing is that after a successful login, the access_token cookie is being sent from the server to the client. Although the cookie is successfully set in th ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Exploring the Google Drive API with Node

Currently, I am utilizing the Google Drive API in NodeJS. Below is the snippet of code I am using to download a file: try { const auth = await authenticate(); const drive = google.drive({ version: 'v3', auth }); drive.files.get( ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Clearing a Vue.js filter: a step-by-step guide

Below is my Vue Js code where I have successfully implemented a filter to API array elements. However, I am facing an issue when trying to set up a button that clears the filter upon clicking, restoring the page to its original state without any changes. ...

Error Alert: The index "dateform" is not defined

I have set up two calendar date pickers and am trying to obtain the input data or retrieve the "post" date. However, upon running my code, I am encountering the following error message: Notice: Undefined index: dateform I am puzzled by this error because ...

Updating React markers dynamically on Google Maps issue

I'm currently developing a transportation app with React and the @react-google-maps/api library. The app includes a map component that displays the real-time location of delivery workers using custom icons. However, I've encountered an issue wher ...

What is the reason for $addToSet always returning 1 upon update?

Recently, I have been utilizing mongoose for my project. I encountered an issue when attempting to update my data in a specific way. model.update({_id: id}, {$addToSet: {refs: refId}}, function(err, numAffected){ console.log(numAffected); }) Although t ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

Obtain a collection of the corresponding keys for a given value from dictionaries

I'm implementing a function that retrieves a list of keys associated with a specific value in the dictionary. Although I am able to print out the first key successfully, I'm facing difficulties in displaying subsequent keys. I understand that I ...

Revising a document by considering the content of a specific element within an array in the document alongside the document's unique identifier

Having trouble getting this update operation to function properly. This is the setup: We have three entities - an Event, a Ticket, and a TicketPurchase. Both the Event and TicketPurchase contain arrays of Ticket as properties. The goal: To update th ...

Building a client-side webservice using the <script> tag in JavaScript

I am currently working on implementing a client-side webservice client. In order to bypass the same server policy, I am considering including an external page that contains the content I need to read using the <script> tag which can fetch cross-doma ...