angular - ประเภท 'SafeResourceUrl' ไม่สามารถกำหนดค่าให้กับประเภท 'string'
ผมกำลังพยายามทำให้ URL ของ PDF ปลอดภัยและต้องการกำหนดมันให้กับตัวแปรประเภทสตริงเพื่อที่ผมจะได้ใช้มันกับตัวดู PDF มีวิธีใดบ้างที่จะทำเช่นนั้น? ถ้าผมใช้ประเภท any สำหรับ pdfSrc ผมจะได้รับ วัตถุพารามิเตอร์ไม่ถูกต้อง: ต้องมี .data, .range หรือ .url ใน <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>
คำตอบ #1
ฉันมีวิธีแก้ไขเรื่องนี้ ฉันลองทำการฆ่าเชื้อ SafeResourceUrl อีกครั้งด้วยวิธี sanitize() ซึ่งค่าที่ส่งกลับเป็น string | null
ในกรณีที่คุณต้องการใช้ 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));
}
