好吧,看起來這個問題有很多答案,但我一直無法理解我應該做什麼。當數據發生變化時重新創建組件
我目前有一個子組件,當有人點擊另一個子組件的播放按鈕時,它正在創建。這是通過與我的父母共享數據的服務發生的,然後父母傳遞數據並創建我的孩子音頻播放器組件。我遇到的問題是,如果用戶導航到另一個頁面並點擊播放該頁面上的音頻,則舊音頻仍然存在,並且新音頻無法啓動。
是否有生命週期掛鉤或我可以用來銷燬舊音頻組件並創建新音頻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'並且卸載(停止/暫停/銷燬)舊的音頻對象,然後加載一個新的音頻對象。 –