Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'SafeResourceUrl' is not assignable to type 'string'

I am trying to sanitize a pdf url and want to assign it to a string type variable so that I can use it for pdf viewer. Is there any way to do that? If I use any type for pdfSrc type, I am getting Invalid parameter object: need either .data, .range or .url in the <pdf-viewer>.

Note: The URL which I used is for reference purpose, i would use external URLs in that place

landingpage.component.ts

import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';

export class LandingpageComponent implements OnInit {
     public pdfSrc: string;
}

constructor(    
    private sanitizer: DomSanitizer) {
}

fnOpenAsset() {     
   let url = 'http://localhost/pdf_viewer-master/18/docs/pdf.pdf';
   this.pdfSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

landingpage.component.html

<pdf-viewer class="alignComponentCenter" [src]="pdfSrc" 
</pdf-viewer>
like image 277
Muthu Avatar asked Apr 25 '19 12:04

Muthu


People also ask

What is Saferesourceurl?

SafeResourceUrllink interface. Marker interface for a value that's safe to use as a URL to load executable code from.

What does bypassSecurityTrustHtml do?

bypassSecurityTrustHtml()linkBypass security and trust the given value to be safe HTML. Only use this when the bound HTML is unsafe (e.g. contains <script> tags) and the code should be executed.

What is SafeUrl in angular?

SafeUrllinkMarker interface for a value that's safe to use as a URL linking to a document.


1 Answers

Future solution

There are efforts from the angular team to make the usage of Safe* types more flexible. As far as I understand issue #33028 on the angular github page they are currently enabling the direct use of Safe* types as string. That way you could be using bypassSecurityTrustResourceUrl() and directly assign the return value to the src property. Excactly as @Muthu tried it initially.

this.pdfSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);

This would affect the following types (as they all extend the SafeValue interface):

  • SafeHtml
  • SafeUrl
  • SafeResourceUrl
  • SafeScript
  • SafeStyle

Current solution

For now it seems like the best workaround to access the actual string is to re-sanitize the Safe* value, just like @Muthu points it out in his accepted answer.

Alternatively one can either use any type or force the return value to be a string by using as string after calling the function. Note that this only works for certain scenarios, e.g. assigning HTML code from SafeHtml.

let html: any = this.sanitizer.bypassSecurityTrustHtml("<h1>just some html!</h1>");
let html2: string = this.sanitizer.bypassSecurityTrustHtml("<h1>even more html!</h1>") as string;
like image 131
JR46 Avatar answered Oct 22 '22 23:10

JR46