即使在全局对象上定义,Angular2上的onYouTubeIframeAPIReady也找不到名称'YT'

时间:2017-12-01 20:25:46

标签: angular typescript youtube-api youtube-iframe-api

为了捕捉用户暂停youtube视频的时间(that question posted here),我发现自己在Angular2中使用了onYouTubeIframeAPIReady回调方法。

我遇到了与herehere概述类似的困难。

我遵循了建议并最终使用了(window as any).onYouTubeIframeAPIReady = function () {}

在我的onYouTubeIframeAPIReady方法中,我有以下代码:

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

我的打字稿linter得到以下错误:

  

类型'{events:{'onReady':( event:any)=>类型的参数无效; 'onStateChange':( event:any)=> void;};}'不能分配给'PlayerOptions

类型的参数

我的最小示例回购可以在这里找到:

git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout stackoverflow
npm install
ng serve

1 个答案:

答案 0 :(得分:1)

使用window['YT']代替YT似乎解决了这个问题:

ngOnInit() {
  var player;

  window['onYouTubeIframeAPIReady'] = function() {
    player = new window['YT'].Player('video', {
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerStateChange(event){
    if (event.data == window['YT'].PlayerState.PAUSED) {
      console.log(player.getCurrentTime());
    }
  }

  function onPlayerReady(event) {
    document.getElementById("pause").addEventListener("click", function() {
      player.pauseVideo();
    });
    document.getElementById("play").addEventListener("click", function() {
      player.playVideo();
    });
  }

  if (!window['YT']){
    var tag = document.createElement('script');
    tag.src = "//www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }
}