Javascript Angular 2 - 例外:错误:资源 URL 上下文中使用的不安全值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39858992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 - EXCEPTION: Error: unsafe value used in a resource URL context
提问by Pete
I am getting the following error:
我收到以下错误:
Angular 2 - EXCEPTION: Error: unsafe value used in a resource URL context
Angular 2 - 例外:错误:在资源 URL 上下文中使用了不安全的值
Could it be related to not having the media item straight away on startup? Or is it related to the URL not being safe? I am trying to sanitize it.
这可能与启动时没有立即拥有媒体项目有关吗?还是与 URL 不安全有关?我正在尝试对其进行消毒。
export class HomeComponent {
sanitizer: DomSanitizationService;
errorMessage: string;
activeMedia: MediaItem = new MediaItem(0, '', '', '', '', '', '');
constructor(
private mediaStorage: MediaStorageService,
private harvesterService: HarvesterService,
sanitizer: DomSanitizationService) {
this.sanitizer = sanitizer;
// Initial call -
harvesterService.getMediaItems(10, 'type', 'category');
let subscription = harvesterService.initialMediaHarvestedEvent.subscribe(() => {
this.activeMedia = mediaStorage.mediaList[0];
let newURL = this.activeMedia.URL + '?rel=0&autoplay=1';
newURL = newURL.replace('watch?v=', 'v/');
this.activeMedia.URL = newURL; //sanitizer.bypassSecurityTrustUrl(newURL);
console.log(newURL);
});
}
cleanURL(oldURL: string): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustUrl(oldURL);
}
}
The template code is:
模板代码为:
<div class="row" >
<iframe
id="video"
class="video"
src="{{ cleanURL(activeMedia.URL) }}"
frameborder="0"
allowfullscreen>
</iframe>
</div>
回答by Pete
UPDATED: After changing the
更新:更改后
src="{{cleanURL(activeMedia.URL)}}"
to:
到:
[src]="cleanURL(activeMedia.URL)"
I'm getting: ORIGINAL EXCEPTION: Error: Required a safe ResourceURL, got a URL
我得到:原始例外:错误:需要一个安全的 ResourceURL,得到一个 URL
which is solved with changing the code within the cleanURL method to:
这是通过将 cleanURL 方法中的代码更改为:
return this.sanitizer.bypassSecurityTrustResourceUrl(oldURL);
Instead of:
代替:
return this.sanitizer.bypassSecurityTrustUrl(oldURL);
回答by Trajche Shoposki
Try with this:
试试这个:
cleanURL(oldURL: string): string {
return this._sanitationService.sanitize(SecurityContext.URL, oldURL);
}