accessing class data in a global scope with typescript

3

I'm developing an app in Angular 2 and I'm using the Youtube API. The Youtube API requires that I implement some functions in the global scope, so I did the following:

export class MyClass {

  dados: any;

  constructor( ... ) {
    ...
  }

  loadAPI(){
    (window as any).onYouTubeIframeAPIReady = function () {
      buildPlayer();
    }

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

}

function buildPlayer(){
  player = new YT.Player('player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  console.log('youtube iframe api ready!');
}

function onPlayerReady(event){
  // AQUI ESTÁ O PROBLEMA
  // Eu quero manipular "dados" dentro dessas funções.
}

function onPlayerStateChange(status){
  // AQUI ESTÁ O PROBLEMA
  // Eu quero manipular "dados" dentro dessas funções.
}

The code loads the API correctly and creates the player, but I can not manipulate the data of the variable that is within the class in these functions. Any ideas how I can resolve this?

    
asked by anonymous 21.03.2017 / 21:19

1 answer

1

The problem is that the dados variable is part of the class scope and these functions are declared outside the class , just adjust that.

Declaring the data variable outside the class will allow it to be accessed outside the class.

dados: any;

export class MyClass {    

    constructor() {

    }

    loadAPI(){
    (window as any).onYouTubeIframeAPIReady = function () {
      buildPlayer();
    }

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

function buildPlayer(){
  player = new YT.Player('player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  console.log('youtube iframe api ready!');
}

function onPlayerReady(event){
    //a variável dados pode ser acessada aqui
    console.log(dados);   
}

function onPlayerStateChange(status){
    //a variável dados pode ser acessada aqui
    console.log(dados);        
}   
    
21.03.2017 / 21:27