2017-02-13 108 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

不一定,但在视图中绑定函数通常不是一个好主意,因为每次运行更改检测时都会调用它。这也可能会导致您的视频不断重新加载,如果每个标签都认为它是变化的(不得不测试自己,但并不真正想知道;-))。 –