要在Stackblitz中重现该问题,请单击GO
导航到包含iframe
的组件,该组件现在可以工作,然后前进和后退,iframe
消失。您必须刷新页面才能再次显示iframe
。
我尝试了一些解决方法:
ngOnDestroy
window['onYouTubeIframeAPIReady'] = null;
中释放对象,但未成功这是如何创建iframe
init() {
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
ngOnInit() {
this.init();
window['onYouTubeIframeAPIReady'] = (e) => {
this.YT = window['YT'];
this.player = new window['YT'].Player('player', {
videoId: '1cH2cerUpMQ'
});
};
}
模板
<div id="player" >
</div>
有人成功解决方法,请分享。
答案 0 :(得分:4)
您可以检查youtube api是否已经初始化,然后只需创建播放器即可。
player: any;
init() {
if (window['YT']) {
this.createPlayer();
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.createPlayer();
}
ngOnInit() {
this.init();
}
createPlayer() {
this.player = new window['YT'].Player('player', {
videoId: '1cH2cerUpMQ'
});
}
ngOnDestroy() {
window['onYouTubeIframeAPIReady'] = null;
if (this.player) {
this.player.destroy();
}
}
答案 1 :(得分:1)
一个星期后,一种变通方法可以工作,但看起来“肮脏”。
实际上,在前进和后退后,功能window['onYouTubeIframeAPIReady']
不再执行。
因此,我在此方法中放入了一个布尔值,如果执行则重置为false
。然后,通过考虑该值来检查是否需要在超时3秒后重新加载
//this.needToReload = true in constructor
ngAfterViewInit(){
let n = 3;
var intervalId= setInterval(() => {
n--;
this.tick = n*10;
if (n === 0) {
clearInterval(intervalId);
if(this.needToReload)
{
location.reload();
}
}
}, 1000);
}
ngOnInit() {
this.init();
window['onYouTubeIframeAPIReady'] = (e) => {
this.YT = window['YT'];
this.needToReload = false;
this.player = new window['YT'].Player('player', {
videoId: '1cH2cerUpMQ'
});
};
}
答案 2 :(得分:0)
如果 youtube api 已经存在,您可以销毁并重新初始化;
public player: any;
public YT: any;
init() {
if (window['YT']) {
window['YT'] = null;
if(this.player){
this.player.destroy();
}
this.init();
}
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.startVideo();
}
ngOnInit() {
this.init();
}
startVideo() {
this.player = new window['YT'].Player('player-youtube', {
videoId: this.linkVideo,
playerVars: {
autoplay: 0,
modestbranding: 1,
controls: 0,
disablekb: 1,
rel: 0,
showinfo: 0,
fs: 0,
playsinline: 1,
loop: 0,
origin: window.location.host,
host: 'https://www.youtube.com'
},
events: {
'onStateChange': this.onPlayerStateChange.bind(this),
'onReady': this.onPlayerReady.bind(this),
}
}
ngOnDestroy() {
window['onYouTubeIframeAPIReady'] = null;
if (this.player) {
this.player.destroy();
}
}