在点击任何玩家名字时,主题会更新,服务会返回一个Observable,我会在组件中显示它。
我试图在进行新的订阅之前取消订阅组件中的可观察对象。有没有方法可以在不使用ngOnDestroy / async管道的情况下做到这一点?
ngOnInit() {
this.playersubscription = this.playerService
.getSelectedPlayer()
.subscribe((player) => {
this.selectedPlayer = player;
// this.playersubscription.unsubscribe(); If I unsubscribe it here , the functionality breaks
});
}
服务项目:
private selectedPlayer = new Subject<string>();
getSelectedPlayer() {
return this.selectedPlayer.asObservable();
}
updateSelectedPlayer(playerName: string) {
this.selectedPlayer.next(playerName);
}
这是我试过的Stackblitz。请帮助,提前感谢!
1条答案
按热度按时间xjreopfe1#
所以我在这里创建了一个子组件(名为hello)。在子组件中,你可以找到你的代码。应用程序组件有一个按钮,可以显示/隐藏子组件。所以你可以看到ngOnInit和ngOnDestroy的控制台日志。
Here是更新的Stackblitz链接。
Hello组件(子组件)
应用程序组件
做你想要的,如果你明白所有你可以选择我的职位作为答案。
你好弗洛里安