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.