如何在Angular 2中设置iframe src而不会导致`unsafe value`exception?
我是Angular 2的新手,没有AngularJS的经验,并且在设置iframe src属性的教程上工作:
<iframe width="100%" height="300" src="{{video.url}}"></iframe> 这引发了一个exception:
 Error: unsafe value used in a resource URL context at DomSanitizationServiceImpl.sanitize... 
 我已经尝试使用绑定与[src]没有成功。 我可能错过了一些东西,我很难find解决办法。 
更新
RC.6 ^版使用DomSanitizer
Plunker
一个很好的select是使用纯粹的pipe道:
 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添加到SafePipe的declarations数组中。  ( 如文档所见 ) 
 @NgModule({ declarations : [ ... SafePipe ], }) 
HTML
 <iframe width="100%" height="300" [src]="url | safe"></iframe> 
Plunker
 如果您使用embed标签,这可能会对您有所帮助: 
- 如何与angular2 rc.6禁用消毒embedded的HTML标签显示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样本
这个为我工作。
 import { Component,Input,OnInit} from '@angular/core'; import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser'; @Component({ moduleId: module.id, selector: 'player', templateUrl: './player.component.html', styleUrls:['./player.component.scss'], }) export class PlayerComponent implements OnInit{ @Input() id:string; url: SafeResourceUrl; constructor (public sanitizer:DomSanitizer) { } ngOnInit() { this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id); } } 
恭喜 ! ¨^^我有一个简单而高效的解决scheme,是的!
 <iframe width="100%" height="300" [attr.src]="video.url"></iframe 
[attr.src]而不是src“video.url”而不是{{video.url}}
太好了)