javascript - Hur inkluderar jag Youtube Iframe API i Angular2?
Jag använder Angular-cli. Jag skulle vilja använda YouTube iframe API inom en Angular2-modul. Jag kunde inte få youtube-iframe node-paketet att fungera. Och de mer Angular2-specifika paketen verkar inte stödja alla API-funktioner.
Här är mitt arbete hittills: Jag har inkluderat själva API:et i min mapp för tillgångar. Jag har lagt till platsen som ett skript i min .angular-cli.json-fil.
Så här ser min AppComponent ut:
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();
}
Det fungerar när jag har utvecklarverktygen öppna i Chrome. Men inte när jag har dem stängda. Detta är felet jag får:
this.YT.Player is not a constructor
at AppComponent.webpackJsonp.328.AppComponent.onYouTubeIframeAPIReady
Jag antar att problemet är att använda window["YT"]. Kan någon ge mig en steg-för-steg-guide för hur man gör detta korrekt?
Svar #1
Detta bör vara ett timing-problem. För onYouTubeIframeAPIReady är det en callback som tillhandahålls av YouTube. Så inne i ngOninit() eller ngAfterViewInit() skulle jag rekommendera att du registrerar den på window-nivå för att låta YouTube API kalla på den när allt är klart.
något som:
(<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();
}
}
});
}
