我正在使用 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"访问它时,它说它是未定义的。我该怎么做?
不确定是否要使用 Angular 2,但我认为它必须是">event.data"。
我在葡萄牙语版本的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);
}
这是一件简单的事情,我想得太复杂了。我希望这对其他人有所帮助。