好吧,看起来这个问题有很多答案,但我一直无法理解我应该做什么。当数据发生变化时重新创建组件
我目前有一个子组件,当有人点击另一个子组件的播放按钮时,它正在创建。这是通过与我的父母共享数据的服务发生的,然后父母传递数据并创建我的孩子音频播放器组件。我遇到的问题是,如果用户导航到另一个页面并点击播放该页面上的音频,则旧音频仍然存在,并且新音频无法启动。
是否有生命周期挂钩或我可以用来销毁旧音频组件并创建新音频onclick的方法?
信息框 - 单击播放按钮时发生初始激活的位置。
export class InfoBoxComponent implements OnInit {
...
activateAudioPlayer(session) {
this.newAudioService.newAudio(session)
}
}
新的音频服务
export class NewAudioService {
newActiveAudioSource: Subject<string> = new Subject<string>();
newAudio(session) {
this.newActiveAudioSource.next(session);
}
newActiveAudio$ = this.newActiveAudioSource.asObservable();
}
前端组件 - 信息框和音频播放器
@Component({
template: `<audio-player *ngIf='newActiveAudio' [newActiveAudio]='newActiveAudio'></audio-player>`,
})
export class FrontendComponent implements OnInit {
...
ngOnInit() {
this.sub = this.newAudioService.newActiveAudio$.subscribe(
newActiveAudio => {
this.newActiveAudio = newActiveAudio;
});
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.sub.unsubscribe();
}
}
InfoBoxComponent是什么被创建,然后销毁多次,这也应该摧毁音频元素? – martin
InfoBoxComponent创建在我的frontendComponent的onInit上,当点击infoBoxComponent中的一个按钮时,创建audioplayerComponent。我这样做,以便用户可以浏览我的网站,并仍然播放音频,直到他们找到他们想要播放的其他选择。问题是一旦audioPlayerComponent被初始化,我需要一种方式来销毁它并用不同的数据重新创建它。对不起,如果我不清楚我的原始问题。 – Jleibham
只是好奇,如果这个工程:'this.sub = this.newAudioService.newActiveAudio $ .subscribe( newActiveAudio => { this.newActiveAudio = NULL; this.newActiveAudio = newActiveAudio; });' 不过,我想比如说你应该在'audio-player'里面使用'OnChange'并且卸载(停止/暂停/销毁)旧的音频对象,然后加载一个新的音频对象。 –