【问题标题】:onYouTubeIframeAPIReady on Angular2 can't find name 'YT' even when defined on global object即使在全局对象上定义,Angular2 上的 onYouTubeIframeAPIReady 也找不到名称“YT”
【发布时间】:2018-05-16 00:11:53
【问题描述】:

为了捕捉用户暂停 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
    }
  });
} 

我的 typescript linter 出现以下错误:

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

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

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

【问题讨论】:

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


    【解决方案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);
      }
    }
    

    【讨论】:

    • 再次感谢@Bertrand Martel!知道为什么会这样吗? window['YT'] 实际上做了什么?
    猜你喜欢
    • 2018-01-30
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多