访问窗口函数typescript上的类数据

时间:2017-03-20 20:32:12

标签: javascript angular typescript youtube-api

我正在使用Angular 2构建应用程序,我也使用YouTube IFrame API。

Youtube API要求我向全局对象声明一些函数,所以这是我的代码:

export class MyClass {

  someData: 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){
  // HERE IS MY PROBLEM
  // I want to manipulate "someData" in these functions
}

function onPlayerStateChange(status){
  // HERE IS MY PROBLEM
}

我想在这些函数中操作来自MyClass的一些数据(即从数据库中检索它),但当我尝试使用" this.data"它说它未定义。我该怎么办?

2 个答案:

答案 0 :(得分:0)

不确定使用Angular 2,但我认为它必须是" event.data "。

答案 1 :(得分:0)

我在葡萄牙语版本的stackoverflow中找到了一些帮助。 我必须做的是在类之外声明变量,就像函数一样。所以它是这样的:

let someData: any;

export class MyClass {    

    someData: any; // after manipulate the data in here, I can just
                   // set it like this: someData = this.someData;  

    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){
    // I can manipulate it here
    console.log(someData);   
}

function onPlayerStateChange(status){
    // I can manipulate it here
    console.log(someData);        
}

这很简单,我觉得太复杂了。我希望这有助于其他人。