一次订阅即可订阅多个 observable

时间:2021-03-07 09:12:52

标签: angular rxjs

在同一个组件中使用相同的订阅订阅不同的 observable 是不好的做法吗?只是为了在 ngOnDestroy() 中取消订阅它们。还是第二个订阅会覆盖第一个订阅?

userSubscription: Subscription;

ngOnInit(): void {

  this.userSubscription = this.userService.add(user)
    .subscribe(response => {
      ...
    })

  this.userSubscription = this.userService.update(user)
    .subscribe(response => {
      ...
  });
}

ngOnDestroy() {
  this.userSubscription.unsubscribe();
}

1 个答案:

答案 0 :(得分:1)

你可以使用订阅的api添加

this.userSubscription.add(
  this.userService.add(user)
  .subscribe(response => {
    ...
  })
)

然后

this.userSubscription.add(
  this.userService.update(user)
  .subscribe(response => {
    ...
  })
)

你只需要一个你想要的退订