2017-07-07 98 views
1

我有一個返回HTML代碼的API(其中包含iframe對象)。角度清潔劑 - YouTube iframe的例外

發送到客戶端的代碼如下所示:

<p>Something blabla</p> 
<iframe allowfullscreen="true" frameborder="0" height="270" src="https://www.youtube.com/embed/someID?feature=oembed" width="480"></iframe> 

現在,我怎麼能在YouTube添加一個例外,僅清潔劑?問題是,HTML代碼是用戶輸入(並非完全用戶輸入,但僅限於我信任的人,因此我猜這沒有安全風險),所以我不能使用bypassSecurityTrustResourceUrl,對吧?

我的代碼(page.component.ts)

constructor(private _router: Router, private _http: Http, private _sanitizer: DomSanitizer) { 
    this.fetchNews(); 
} 

fetchNews() { 
    this._http 
     .get(this.urlAPI) 
     .map((response: Response) => { 
     let json = response.json(); 
     this.content = json.results[0].content; 
     }).subscribe(); 
} 

和HTML(page.component.html):

<div [innerHTML]="content"> 
</div> 
+0

沒有你發現同樣的任何解決方案,因爲我也面臨同樣的問題 –

+0

不幸的是沒有,但如果我這樣做,我會在這裏發佈的解決方案。 – GTX

回答

0

只需用創建管道CLI

離子g管Youtube

然後導入domsanatizer在管文件

import { DomSanitizer } from '@angular/platform-browser'; 

進口管在app.module.ts

import {Youtube } from '../pipes/youtube'; 

然後在聲明

申報管見下文youtube.ts管道文件

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

/** 
* Generated class for the Youtube pipe. 
* 
* See https://angular.io/docs/ts/latest/guide/pipes.html for more info on 
* Angular Pipes. 
*/ 
@Pipe({ 
    name: 'youtube', 
}) 
export class Youtube implements PipeTransform { 
    constructor (private dom:DomSanitizer) { 

    } 
    transform(value: string, args) { 
    return this.dom.bypassSecurityTrustHtml(value); 
    } 
} 

最後一步你的HTML代碼:

<div [innerHTML]="content | youtube"> 
</div>