首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >键入“SafeResourceUrl”不能指定键入“string”

键入“SafeResourceUrl”不能指定键入“string”
EN

Stack Overflow用户
提问于 2019-04-25 12:34:10
回答 4查看 26.9K关注 0票数 17

我试图清理一个pdf url,并希望分配给一个字符串类型变量,以便我可以使用它的pdf查看器。有什么办法吗?如果我将any类型用于pdfSrc类型,我将得到Invalid parameter object: need either .data, .range or .url in the <pdf-viewer>

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

landingpage.component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
<pdf-viewer class="alignComponentCenter" [src]="pdfSrc" 
</pdf-viewer>
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-04-25 13:23:59

我有办法解决这个问题。我再次尝试用返回值为string的SafeResourceUrl方法对sanitize()进行清理。

如果您想使用bypassSecurityTrustUrl(),那么SecurityContext.URL就会发生。在我的例子中,我使用了SecurityContext.RESOURCE_URL

代码语言:javascript
复制
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));
}
票数 39
EN

Stack Overflow用户

发布于 2019-04-25 12:45:26

如前所述,您只需删除变量声明(或声明any类型),但我怀疑许多人会同意正确的解决方案。

各种Dom清除器方法不返回字符串,它们返回各种对象类型。

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

代码语言:javascript
复制
this.sanitizer.bypassSecurityTrustResourceUrl(url);

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

票数 1
EN

Stack Overflow用户

发布于 2020-10-14 09:35:35

未来解决方案

棱角小组努力使Safe*类型的使用更加灵活。就我所理解的角度github页面上的第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代码。

代码语言:javascript
复制
let html: any = this.sanitizer.bypassSecurityTrustHtml("<h1>just some html!</h1>");
let html2: string = this.sanitizer.bypassSecurityTrustHtml("<h1>even more html!</h1>") as string;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55849415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档