提问者:小点点

如何在不使用ngOnDestroy或异步管道的情况下退订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个答案

匿名用户

所以在这里我创建了一个子组件(名为 hello)。在孩子体内,您将找到您的代码。应用程序组件有一个按钮,将显示/隐藏孩子。所以你会看到ngOnInit和ngOnDestroy的console.logs。

这是更新的Stackblitz链接。

你好组件(子组件)

export class HelloComponent implements OnInit, OnDestroy {
  selectedPlayer: string;
  playersubscription: Subscription;

  constructor(private playerService: PlayerService) {}

  ngOnInit() {
    console.log('ngOnInit');
    this.playersubscription = this.playerService
      .getSelectedPlayer()
      .subscribe((player) => {
        this.selectedPlayer = player;
        // this.playersubscription.unsubscribe(); If I unsubscribe it here , the functionality breaks
      });
  }

  ngOnDestroy() {
    this.playersubscription.unsubscribe();
    console.log('ngOnDestroy');
  }

  players = [
    {
      name: 'Sachin',
      team: 'MI',
    },
    {
      name: 'Dhoni',
      team: 'CSK',
    },
    {
      name: 'Kohli',
      team: 'RCB',
    },
  ];

  selectPlayer(playerName) {
    this.playerService.updateSelectedPlayer(playerName);
  }
}

应用组件

export class AppComponent {
  showChild: boolean = true;

  constructor() {}
  onShowHideClick() {
    this.showChild = !this.showChild;
  }
}


..... and HTML part

<h1>APP COMPONENT</h1>
<button (click)="onShowHideClick()">SHOW / HIDE children</button>
<hr />
<hello *ngIf="showChild"></hello>

问候,弗洛里安

相关问题