2

In an effort to capture the time at which a user pauses a youtube video (that question posted here), I have found myself using the onYouTubeIframeAPIReady callback method in Angular2.

I am having similar difficulties as outlined here and here.

I followed the advice and ended up using (window as any).onYouTubeIframeAPIReady = function () {}.

In my onYouTubeIframeAPIReady method, though, I have the following code:

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

I get the following error from my typescript linter:

Argument of type '{events: {'onReady':(event:any) => void; 'onStateChange': (event:any)=>void;};}' is not assignable to parameter of type 'PlayerOptions

My minimal example repo can be found here:

git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout stackoverflow
npm install
ng serve
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Atticus29
  • 4,190
  • 18
  • 47
  • 84

1 Answers1

3

Using window['YT'] instead of YT seems to solve this :

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
  • 42,756
  • 16
  • 135
  • 159