【发布时间】: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