如何在Angular 2中设置iframe src而不会导致`unsafe value`异常?

我是没有AngularJS经验的Angular 2的新手,并且正在编写一个涉及设置iframe src属性的教程:

<iframe width="100%" height="300" src="{{video.url}}"></iframe>

这引发了一个异常:

Error: unsafe value used in a resource URL context
at DomSanitizationServiceImpl.sanitize...

我已经尝试使用[src]绑定但没有成功.我可能错过了一些东西,我很难找到解决方案.

最佳答案
更新v8

下面的答案工作,但exposes your application to XSS security risks!.
而不是使用this.sanitizer.bypassSecurityTrustResourceUrl(url),建议使用this.sanitizer.sanitize(SecurityContext.URL,url)

更新

对于RC.6 ^版本使用DomSanitizer

Plunker

一个很好的选择是使用纯管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
} 

记得将新的SafePipe添加到AppModule的声明数组中. (as seen on documentation)

@NgModule({
   declarations : [
     ...
     SafePipe
   ],
})

HTML

<iframe width="100%" height="300" [src]="url | safe"></iframe>

Plunker

如果您使用embed标签,这可能对您有意义:

> how with angular2 rc.6 disable sanitize on embed html tag which display pdf

旧版RC.5

您可以像这样利用DomSanitizationService:

export class YourComponent {
  url: SafeResourceUrl;
  constructor(sanitizer: DomSanitizationService) {
    this.url = sanitizer.bypassSecurityTrustResourceUrl('your url');
  }
}

然后绑定到模板中的url:

<iframe width="100%" height="300" [src]="url"></iframe>

不要忘记添加以下导入:

import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';

Plunker sample

转载注明原文:如何在Angular 2中设置iframe src而不会导致`unsafe value`异常? - 代码日志