如何使用Youtube链接设置iframe?

时间:2018-04-10 14:39:20

标签: javascript angular youtube angular5

它下载文件而不是播放。我完全不明白为什么,因为我正在做一个教程。

组件:

public infoPage: InfoPage;
public trustUrl: SafeResourceUrl;
constructor(
    public oAuthService: OAuthService,
    private dataService: DataService,
    public router: Router,
    public route: ActivatedRoute,
    private sanitizer: DomSanitizer
) {
    this.route.params.subscribe(params => {
        if (params['id']) {
            this.dataService.get<InfoPage>('api/infopages/' + params['id'])
                .subscribe(infoPage => {
                    this.updateVideoUrl(infoPage);
                    this.infoPage = infoPage;
                });
        }
    });
}
public ngOnInit() {
    this.infoPage = {};
}

public updateVideoUrl(infoPage: InfoPage) {
    if (infoPage == null || infoPage.youtubeVideoUrl == null)
        return "";
    this.trustUrl =
        this.sanitizer.bypassSecurityTrustResourceUrl(infoPage.youtubeVideoUrl.replace("watch?v=", "v/"));
}

并查看

 <iframe width="560" height="315" class="e2e-iframe-trusted-src" [src]="trustUrl" allowfullscreen></iframe>

1 个答案:

答案 0 :(得分:0)

您可以使用此简单组件为您构建iframe HTML

https://github.com/SamirHodzic/ngx-embed-video

一点提示是生成的字符串必须在div innerHTML属性绑定中使用。像这样:

<div [innerHTML]="youtubeEmbedPlayer"></div>

在您的.ts文件中:

import { Component } from '@angular/core';
import { EmbedVideoService } from 'ngx-embed-video';

@Component({
  selector: 'app-component',
  template: '<div [innerHtml]="iframe_html"></div>',
})
export class AppComponent {
  youtubeEmbedPlayer: any;
  youtubeUrl = "https://www.youtube.com/watch?v=iHhcHTlGtRs";

  constructor(
    private embedService: EmbedVideoService
  ) {
    this.youtubeEmbedPlayer = this.embedService.embed(youtubeUrl);
  )
}

此组件 - ngx-embed-video - 将操作来自youtube / vimeo / dailymotion的网址,以生成正确的iframe设置。像魔术一样..