2017-05-31 63 views
2

我正在使用Angular-cli。我想在Angular2模塊中使用youtube iframe api。我無法使youtube-iframe node package正常工作。而更多的Angular2特定軟件包似乎並不支持完整的api功能。如何在Angular2中包含Youtube Iframe API?

以下是我的工作到目前爲止: 我已將actual api包括在我的資產文件夾中。我在.angular-cli.json文件中將該位置添加爲腳本。

這是我AppComponent是什麼樣子:

export class AppComponent { 
YT; 
constructor(){ 
    this.YT = window["YT"]; 
} 

onYouTubeIframeAPIReady() { 
    console.log(this.YT); 
    var player; 
    player = new this.YT.Player('muteYouTubeVideoPlayer', { 
     videoId: 'KKYYAbGpw6A', // YouTube Video ID 
     width: 560,    // Player width (in px) 
     height: 316,    // Player height (in px) 
     playerVars: { 
      autoplay: 1,  // Auto-play the video on load 
      controls: 0,  // Show pause/play buttons in player 
      showinfo: 0,  // Hide the video title 
      modestbranding: 0, // Hide the Youtube Logo 
      loop: 1,   // Run the video in a loop 
      fs: 0,    // Hide the full screen button 
      cc_load_policy: 0, // Hide closed captions 
      iv_load_policy: 0, // Hide the Video Annotations 
      autohide: 1   // Hide video controls when playing 
     }, 
     events: { 
      onReady: function(e) { 
      e.target.mute(); 
      } 
     } 
    }); 
} 

ngAfterViewInit(){ 
    this.onYouTubeIframeAPIReady(); 
} 

它工作時,我有在Chrome中打開devTools。但是,當我把它們關閉時不行。這是我得到的錯誤:

this.YT.Player is not a constructor 
at AppComponent.webpackJsonp.328.AppComponent.onYouTubeIframeAPIReady 

我想問題是使用window["YT"]。任何人都可以提供一步一步的指導,做到這一點正確嗎?

回答

0

這應該是timing問題。對於onYouTubeIframeAPIReady,這是一個youtube提供的回調。因此,在ngOninit() or ngAfterViewInit()之內,我建議您在window級別註冊它,讓youtube API在一切準備就緒時調用它。

類似:

(<any>window).onYouTubeIframeAPIReady =()=>{ 
    console.log((<any>window).YT); 
    this.player = new (<any>window).YT.Player('muteYouTubeVideoPlayer', { 
     videoId: 'KKYYAbGpw6A', // YouTube Video ID 
     width: 560,    // Player width (in px) 
     height: 316,    // Player height (in px) 
     playerVars: { 
      autoplay: 1,  // Auto-play the video on load 
      controls: 0,  // Show pause/play buttons in player 
      showinfo: 0,  // Hide the video title 
      modestbranding: 0, // Hide the Youtube Logo 
      loop: 1,   // Run the video in a loop 
      fs: 0,    // Hide the full screen button 
      cc_load_policy: 0, // Hide closed captions 
      iv_load_policy: 0, // Hide the Video Annotations 
      autohide: 1   // Hide video controls when playing 
     }, 
     events: { 
      onReady: function(e) { 
      e.target.mute(); 
      } 
     } 
    }); 
}