在 Angular 5 中,我想在 iFrame
中显示 map .我使用了安全管道,但是在控制台中收到错误
Required a safe ResourceURL, got a HTML
这是我的代码
.ts
文件:import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';
export class XXXComponent implements OnInit {
constructor(private sanitizer: DomSanitizer){}
this.mapURL = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDdWRYxwcpnrJWXbsR4fmP3HwvsFlCMYPk&q=Ylistörmä+1,+02210+Espoo,+Finland&attribution_source=Google+Maps+Embed+API";
this.urlsafe = this.createSafeMap(this.mapURL);
createSafeMap(url){
return this.sanitizer.bypassSecurityTrustHtml(url);
}
在 .html
文件,我执行以下操作以在 iframe 中显示 map :<iframe [src]="urlsafe | safe: 'html'"></iframe>
以下是safe.pipe.ts
的内容:import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
最佳答案
为了安全地使用 url 你只需要写 safe
管带 resourceUrl
参数并扔掉你的 urlsafe
包装器:
[src]="mapURL | safe: 'resourceUrl'"
关于安全管道中的 Angular 5 出现错误 - 需要一个安全的 ResourceURL,得到一个 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905150/