类型“ SafeResourceUrl”不可分配给“字符串”类型

时间:2019-04-25 12:34:11

标签: angular typescript pdf-viewer

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

注意:我使用的URL仅供参考,我会在该位置使用外部URL

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>

4 个答案:

答案 0 :(得分:0)

取出变量声明

pdfSrc : any;

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

答案 1 :(得分:0)

正如已经建议的那样,您可以删除变量声明(或声明any类型),但是我怀疑很多人都同意这是正确的解决方案。

各种Dom消毒剂方法不返回字符串,它们返回各种对象类型。

请参阅官方API文档:https://angular.io/api/platform-browser/DomSanitizer

this.sanitizer.bypassSecurityTrustResourceUrl(url);

返回SafeResourceUrl类型的对象,而不是字符串;因此,您的声明应该反映这种类型,而不是模糊的any类型。

答案 2 :(得分:0)

我有办法解决这个问题。我尝试使用返回值是字符串|的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));
}```

答案 3 :(得分:0)

未来解决方案

角度小组的努力使Safe*类型的使用更加灵活。据我了解,在有角的github页面上的issue #33028目前正在将Safe*类型直接用作string。这样,您可以使用bypassSecurityTrustResourceUrl()并将返回值直接分配给src属性。正是@Muthu最初尝试过的。

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

这会影响以下类型(因为它们都扩展了SafeValue接口):

  • SafeHtml
  • SafeUrl
  • SafeResourceUrl
  • SafeScript
  • SafeStyle

当前解决方案

目前看来,访问实际字符串的最佳解决方法是重新净化Safe*值,就像@Muthu在其可接受的答案中指出的那样。

或者,可以在调用函数后使用any类型或通过使用as string强制返回值为字符串。请注意,这仅适用于某些情况,例如从SafeHtml分配HTML代码。

let html: any = this.sanitizer.bypassSecurityTrustHtml("<h1>just some html!</h1>");
let html2: string = this.sanitizer.bypassSecurityTrustHtml("<h1>even more html!</h1>") as string;