Search code examples
angulartypescriptpdf-viewer

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>

Solution

  • I got a way to fix this. I tried sanitizing the SafeResourceUrl again with sanitize() method whose return value is string | null.

    In case you want to use bypassSecurityTrustUrl(), then SecurityContext.URL will take place. In my case I used SecurityContext.RESOURCE_URL

    
    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.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(url));
    }