📜  Angular RxJs 我什么时候应该取消订阅“订阅”-TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:37.701000             🧑  作者: Mango

代码示例1
// You don't need to have bunch of subscriptions and unsubscribe manually.
// Use Subject and takeUntil combo to handle subscriptions like a boss:


import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

export class ViewRouteComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject = new Subject()

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 2 */ })

    //...

    this.titleService.emitterN$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.componentDestroyed$.next(true)
    this.componentDestroyed$.complete()
  }
}