【问题标题】:angular 2 - how embed youtube videoangular 2 - 如何嵌入 youtube 视频
【发布时间】:2017-02-13 09:07:53
【问题描述】:

我得到了这个代码

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

问题:angular 会输出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 

【问题讨论】:

  • 使用我在下面的答案中链接到的答案中显示的管道告诉 Angular sanitizer 它应该将 URL 视为安全的。

标签: angular


【解决方案1】:

如果您想从变量中获取 URL,您需要使用 []{{}} 启用绑定(切勿同时使用,{{}} 仅适用于字符串,不适用于对象或数组):

[src]="topic.video.url"

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

如果 URL 被 DOM sanitizer 删除,您可以使用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"

但管道更易于重复使用。

【讨论】:

  • src="{{sanitizer.bypassSecurityTrustResourceUrl(topic.video.url)}}" 会报错,我用对了吗?
  • @angrykiwi 使用属性绑定
  • 不一定,但在视图中绑定函数通常不是一个好主意,因为每次运行更改检测时都会调用它。如果&lt;video&gt; 标签每次都将其识别为更改,这也可能导致您的视频不断重新加载(必须测试自己,但真的不想知道;-))。
  • 你为什么坚持这种糟糕的风格而不是使用管道?
  • 我不知道,只是不知道该怎么做。
猜你喜欢
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2012-06-25
  • 1970-01-01
相关资源
最近更新 更多