在 Angular 6 中导入 YouTube iframe API 的简单方法?

Simplese way to import YouTube iframe API in Angular 6?

所以我需要跟踪我们应用中嵌入的 youtube 的观看时间等,我认为最好的方法是使用 YouTube iframe API 并监听事件,但在模板中使用 (onReady) ,然后将其分配给控制器中的方法 - 显而易见的方法似乎不起作用:

文档显示了这种方法(https://developers.google.com/youtube/iframe_api_reference),但它在模板中包含了脚本标签,我需要一种 angular 方法来完成它而无需在 html 中放置太多 ts , 并且破坏了项目的整体一致性,而且文档没有说明如何在 Angular2 中做到这一点,

从那时起,我找到了一种方法,通过从 Whosebug 答案中获取参考

在您的模板中: <div #ytPlayer id="ytPlayer"></div>

在 ts ngAfterViewinit 中:

ngAfterViewInit() {
const doc = (<any>window).document;
const playerApiScript = doc.createElement('script');
playerApiScript.type = 'text/javascript';
playerApiScript.src = 'https://www.youtube.com/iframe_api';
doc.body.appendChild(playerApiScript);
}

然后监听 iFrame 在 window 完成加载时触发的事件 api:

(<any>window).onYouTubeIframeAPIReady = () => {
  this.player = new (<any>window).YT.Player('ytPlayer', {
    height: '500px',
    width: '100%',
    videoId: 'hHMyZR87VvQ',
    playerVars: { 'autoplay': 0, 'rel': 0, 'controls': 2 },
    events: {
      'onReady': (event) => {
        console.log('Player is ready');
      },
      'onStateChange': (event) => {
      }
    }
  });
};

然后您可以调用播放器上的 getCurrentTime() 等方法或您分配给它的任何变量。

编辑:它仍然使用文档和 window 对象而不是 angular 元素引用,一旦找到使用 window/document 的方法,我将更新此答案.