首页 > 解决方案 > 类型“SafeResourceUrl”不可分配给类型“字符串”

问题描述

我正在尝试清理 pdf url 并希望将其分配给字符串类型变量,以便我可以将其用于 pdf 查看器。有没有办法做到这一点?如果我将anytype 用于 pdfSrc 类型,我会得到Invalid parameter object: need either .data, .range or .url in the <pdf-viewer>.

注意:我使用的 URL 仅供参考,我会在那个地方使用外部 URL

登陆页面.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);
}

登陆页面.component.html

<pdf-viewer class="alignComponentCenter" [src]="pdfSrc" 
</pdf-viewer>

标签: angulartypescriptpdf-viewer

解决方案


我有办法解决这个问题。sanitize()我尝试使用返回值为字符串的方法再次清理 SafeResourceUrl | 无效的。

如果你想使用bypassSecurityTrustUrl(),那么SecurityContext.URL就会发生。在我的情况下,我使用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));
}```

推荐阅读