angular 2 - 如何嵌入 youtube 视频

标签 angular

我得到了这个代码

 <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

这是 Gunter 回答后的结果。

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 

最佳答案

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

[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);

并改为绑定(bind)到这个

[src]="myUrl"

但管道的可重用性更高。

关于angular 2 - 如何嵌入 youtube 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42200287/

相关文章:

Angular2 - 禁用 RouterLink

javascript - url 中没有哈希字符的情况下,Angular2 的 spa 路由如何工作?

c# - 以 Angular 发布文件

c# - 与 ASP.NET Core 中的 FromBody 混淆

javascript - 如何从 Observable (rxjs) 获取更改的元素

angular - 如何从区分大小写的查询参数变量中获取值?

Angular2 - "Can' t 绑定(bind)到 'ngSwitchWhen',因为它不是 'template' 的已知属性。”

css - 模块化进度条

javascript - 使用多个 promise 的区域符号 currentTask Ionic2 错误

json - 为什么 Angular 4 中的 httpclient 假设请求正在发送 json 数据