onYouTubeIframeAPIReady on Angular2 can't find

2020-04-11 09:48发布

I'm trying to insert the YouTube embed API on my angular 2 project, built with angular cli.

I get a "can't find name 'YT'" when I try the approach commented on this question: onYouTubeIframeAPIReady not firing on angular2 web app

My service code looks like this:

loadAPI() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

(window as any).onYouTubeIframeAPIReady = function () {
  this.player = new YT.Player('player', {
    events: {
      'onReady': this.onPlayerReady,
      'onStateChange': this.onPlayerStateChange
    }
  });
};

(window as any).onPlayerReady = function (event) {
  event.target.playVideo();
};

(window as any).onPlayerStateChange = function (status) {
  console.log(status.data);
};

I'm not sure where and how should I get the 'YT'structure. I know it comes from the "https://www.youtube.com/iframe_api", but I have no idea of how to get angular to work this out.

1条回答
姐就是有狂的资本
2楼-- · 2020-04-11 10:44

Adding this to my imports for the file referencing YT seems to work.

import 'youtube';

Can someone please explain why! I realize this is similar to import * from 'moment'; but I never really understood that either.

查看更多
登录 后发表回答