Angular 2 - 迭代不安全值的iframe数组

时间:2017-02-13 10:44:57

标签: angular

我有iframe数组需要进行交互。问题是,当我这样做时,我收到错误un safe value

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../shared/data';

@Component({
    template: `
        <div>Feed</div>
            <div *ngFor="let topic of topics; trackBy: trackByFn">
                <div *ngIf="topic.type == 'discussion'">
                    <div *ngIf="topic.video">
                        <div class="video-container">
                            <iframe src="{{topic.video.url}}" ></iframe>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `
})
export class CompanyComponent implements OnInit {
    constructor(
        private dataService: DataService
    ) {}
    ngOnInit() {
        this.topics = this.dataService.topics;
    }
}

错误

Error: Uncaught (in promise): Error: Error in ./CompanyComponent class CompanyComponent - inline template:29:41 caused by: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
I see similar post, there is solution to deal with un safe value however they do not show how to deal with array of iframes. That the solution I'm looking for.

1 个答案:

答案 0 :(得分:2)

在处理url,script,html,resource时需要绕过安全性:

例如:

自定义管道:

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

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

其他组件:

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <iframe [src]="'https://www.youtube.com/embed/' + testRequestId | safeUrl" width="560" height="315" allowfullscreen></iframe>
  `
})
export class AppComponent {
  testRequestId = 'uelHwf8o7_U';

}

演示:https://embed.plnkr.co/PJQx02/

你的案子:

<iframe [src]="topic.video.url | safeUrl" ></iframe>

文件:https://angular.io/docs/ts/latest/guide/security.html