如何在Angular 2中设置iframe src而不会导致`unsafe value`异常? [英] How to set iframe src in Angular 2 without causing `unsafe value` exception?

查看:3950
本文介绍了如何在Angular 2中设置iframe src而不会导致`unsafe value`异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是没有AngularJS经验的Angular 2的新手,并参与了一个涉及设置iframe src属性的教程:

I am new to Angular 2 without AngularJS experience and working on a tutorial involving the setting of an iframe src attribute:

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

这会引发异常:

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

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

I have already tried using bindings with [src] with no success. I am probably missing something and I have had a hard time finding a solution to this.

推荐答案

更新

For RC.6 ^ 版本使用 DomSanitizer

Plunker

Plunker

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

And a good option is using pure pipe for that:

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的声明数组。 (如文档所示

remember to add your new SafePipe to the declarations array of the AppModule. (as seen on documentation)

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

html

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

Plunker

Plunker

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

If you use embed tag this might be interesting for you:

  • 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 在您的模板中:

And then bind to url in your template:

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

不要忘记添加以下导入:

Don't forget to add the following imports:

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

Plunker样本

Plunker sample

这篇关于如何在Angular 2中设置iframe src而不会导致`unsafe value`异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆