Búsqueda de sitios web

javascript - ¿Cómo incluyo la API de Iframe de Youtube en Angular2?


Estoy usando Angular-cli. Me gustaría utilizar la API de iframe de YouTube dentro de un módulo de Angular2. No pude hacer que funcionara el paquete youtube-iframe de Node. Y los paquetes más específicos de Angular2 no parecen soportar todas las funciones de la API.

Aquí está mi trabajo hasta ahora: He incluido la API real en mi carpeta de recursos. He agregado la ubicación como un script dentro de mi archivo .angular-cli.json.

Así es como se ve mi 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();
}

Funciona cuando tengo las herramientas de desarrollo abiertas en Chrome. Pero no cuando las tengo cerradas. Este es el error que recibo:

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

Supongo que el problema es usar window["YT"]. ¿Alguien puede proporcionarme una guía paso a paso para hacer esto correctamente?

Respuesta #1

Esto debería ser un asunto de temporización. Para el onYouTubeIframeAPIReady, es un callback proporcionado por YouTube. Así que dentro de ngOninit() o ngAfterViewInit(), te recomendaría registrarlo a nivel de window para permitir que la API de YouTube lo llame cuando todo esté listo.

algo como:

(<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();
          }
        }
    });
}