typescript 如何在不使用ngOnDestroy或异步管道的情况下取消订阅可观察对象?

oknrviil  于 2022-12-01  发布在  TypeScript
关注(0)|答案(1)|浏览(127)

在点击任何玩家名字时,主题会更新,服务会返回一个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。请帮助,提前感谢!

xjreopfe

xjreopfe1#

所以我在这里创建了一个子组件(名为hello)。在子组件中,你可以找到你的代码。应用程序组件有一个按钮,可以显示/隐藏子组件。所以你可以看到ngOnInitngOnDestroy的控制台日志。
Here是更新的Stackblitz链接。

Hello组件(子组件)

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>

做你想要的,如果你明白所有你可以选择我的职位作为答案。
你好弗洛里安

相关问题