2016-12-30 66 views
2

好吧,看起来这个问题有很多答案,但我一直无法理解我应该做什么。当数据发生变化时重新创建组件

我目前有一个子组件,当有人点击另一个子组件的播放按钮时,它正在创建。这是通过与我的父母共享数据的服务发生的,然后父母传递数据并创建我的孩子音频播放器组件。我遇到的问题是,如果用户导航到另一个页面并点击播放该页面上的音频,则旧音频仍然存在,并且新音频无法启动。

是否有生命周期挂钩或我可以用来销毁旧音频组件并创建新音频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(); 
    } 
} 
+0

InfoBoxComponent是什么被创建,然后销毁多次,这也应该摧毁音频元素? – martin

+0

InfoBoxComponent创建在我的frontendComponent的onInit上,当点击infoBoxComponent中的一个按钮时,创建audioplayerComponent。我这样做,以便用户可以浏览我的网站,并仍然播放音频,直到他们找到他们想要播放的其他选择。问题是一旦audioPlayerComponent被初始化,我需要一种方式来销毁它并用不同的数据重新创建它。对不起,如果我不清楚我的原始问题。 – Jleibham

+1

只是好奇,如果这个工程:'this.sub = this.newAudioService.newActiveAudio $ .subscribe( newActiveAudio => { this.newActiveAudio = NULL; this.newActiveAudio = newActiveAudio; });' 不过,我想比如说你应该在'audio-player'里面使用'OnChange'并且卸载(停止/暂停/销毁)旧的音频对象,然后加载一个新的音频对象。 –

回答

0

一种可能的方法可以设置的父组件this.newActiveAudio = false然后让角更新setTimeout()视图然后设置新值为newActiveAudio

this.sub = this.newAudioService.newActiveAudio$.subscribe(newActiveAudio => { 
    this.newActiveAudio = false; 
    setTimeout(() => { 
     this.newActiveAudio = newActiveAudio; 
    }); 
}); 
+0

很酷的作品!它带来的唯一问题是旧音频会继续播放,但我认为这是因为我正在动态添加音频文件。我确信我可以杀掉音频播放器的音频元素。 – Jleibham

+0

我不确定从DOM中删除元素会阻止它播放,但... – martin

相关问题