2017-02-13 229 views
4

我得到這個代碼角2 - 如何嵌入YouTube視頻

<div *ngIf="topic.video"> 
     <div class="video-container"> 
      <iframe width="300" height="169" src="topic.video.url" style="border:0"></iframe> 
     </div> 
    </div> 

問題:角將輸出src="localhost://8001"代替src="https://www.youtube.com/embed/hr4BbdUiTUM"

出了什麼問題嗎?

更新2

這是岡特的答案後得到的。

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

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

     ngOnInit() { 
      this.topics = this.dataService.topics; 
     } 
    } 

我仍然得到這個錯誤

company.ts?ac6a:121 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 
+0

使用下面我回答中鏈接到的答案中所示的管道告訴Angular衛生洗滌劑它應該將URL視爲安全。 –

回答

3

如果你想使用[]{{}}(永遠都在同一時間得到您需要啓用綁定變量的URL,{{}}只有作品字符串,而不是物體或陣列):

[src]="topic.video.url" 

src="{{topic.video.url}}" 

如果URL中使用DOM的消毒劑去除得到,你可以使用一個管道一樣顯示在In RC.1 some styles can't be added using binding syntax

import { Pipe, DomSanitizer } from '@angular/core'; 

@Pipe({name: 'safeResourceUrl'}) 
export class SafeResourceUrl { 
    constructor(private sanitizer:DomSanitizer){} 

    transform(url) { 
    return this.sanitizer.bypassSecurityTrustResourceUrl(url); 
    } 
} 
[src]="topic.video.url | safeResourceUrl" 

你也可以申請

this.myUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.topic.video.url); 

和綁定代之以

[src]="myUrl" 

但管道更可重複使用。

+0

src =「{{sanitizer.bypassSecurityTrustResourceUrl(topic.video.url)}}」會給出錯誤,我是否正確使用它? –

+0

@angrykiwi使用屬性綁定代替 –

+0

不一定,但在視圖中綁定函數通常不是一個好主意,因爲每次運行更改檢測時都會調用它。這也可能會導致您的視頻不斷重新加載,如果每個標籤都認爲它是變化的(不得不測試自己,但並不真正想知道;-))。 –