【问题标题】:Youtube API wont load without refreshing my Angular AppYoutube API 不会在不刷新我的 Angular 应用程序的情况下加载
【发布时间】:2021-01-11 12:26:51
【问题描述】:

如果不刷新页面,我无法将 YouTube Iframe API 加载到我的 Angular 应用程序中。在页面加载时,iframe 加载没有任何问题,但是当通过页面路由导航到页面时,API 不会被调用并且 iframe 不会呈现。我在网上看到了一些解决方案,但它们似乎不起作用。

任何帮助将不胜感激。

**HTML**

<div *ngIf="selectedVideo && ytLoading">
    <div id="player" style=" height: 500px; width: 100%;">
</div>

组件

 ytLoading = false;
  player: any;

  
  init() {
    this.ytLoading = true;
    console.log('loading init',this.ytLoading)
    if (this.ytLoading && window['YT'] ) {
    
      this.cueVideoById(this.selectedVideo);
      return;
    }
    var tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  
    window['onYouTubeIframeAPIReady'] = () => this.cueVideoById(this.selectedVideo);
    console.log('WINDOW OBJ 2', window['YT'], 'API SCRIPT 2', tag )
   
  }

  ngOnInit() {


    this.ytLoading = false;
    this.init();

  }

  ngOnDestroy() {
    this.ytLoading = false;

    window['onYouTubeIframeAPIReady'] = null;
    if (this.player) {
      this.player.destroy();
    }
  }


  cueVideoById(selectedVideo) {
    console.log('hits via init', selectedVideo)
    this.player = new window['YT'].Player('player', {
      videoId: selectedVideo.id,
      playerVars: {
        modestbranding: 1,
        controls: 1,
        disablekb: 1,
        rel: 0,
        showinfo: 0,
        fs: 0,
        playsinline: 1
      },
      events: {
        'onStateChange': this.onPlayerStateChange.bind(this),
        'onError': this.onPlayerError.bind(this),
        'onReady': this.onPlayerReady.bind(this),
        
      }
    });


  }

【问题讨论】:

    标签: javascript angular typescript youtube-api


    【解决方案1】:

    问题已通过更新 ngOnDestroy 方法解决

     ngOnDestroy() {
        window['YT'] = null;
        if (this.player) {
          this.player.destroy();
        }
      }
    
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 2020-10-09
      • 2015-09-22
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多