Angular RxJs 各种解订阅方式

昨天说到了将资料订阅出来渲染在页面上的事,那麽就就来说说 RxJs 解订阅这件事吧。
这也是为了避免 memory leak,或重覆订阅所造成的 BUG,若非有限订阅,通常在订阅离开後,都需要解订阅。


转换为的 Observable

first

只执行第一次,通常用於第一次进来读取成功取得资料後,就不需再次执行

export class RxjsOndestroyComponent implements OnInit, OnDestroy {
  private destroy$: Subject<boolean> = new Subject();
  private timer$: Observable<number> = timer(0, 1000);

  constructor() {}

  ngOnInit(): void {
    this.timer$.pipe(first()).subscribe((time) => {
      console.log("time", time);
      this.count = time;
    });
  }
}

take(1)

只发生一次

export class RxjsOndestroyComponent implements OnInit, OnDestroy {
  private destroy$: Subject<boolean> = new Subject();
  private timer$: Observable<number> = timer(0, 1000);

  constructor() {}

  ngOnInit(): void {
    this.timer$.pipe(first()).subscribe((time) => {
      console.log("time", time);
      this.count = time;
    });
  }
}

take1 与 first 差异


takeUntil

持续执行,直到离开

export class RxjsOndestroyComponent implements OnInit, OnDestroy {
  private destroy$: Subject = new Subject<void>();
  private timer$: Observable<number> = timer(0, 1000);

  constructor() {}

  ngOnInit(): void {
    this.timer$.pipe(takeUntil(this.destroy$)).subscribe((time) => {
      console.log("time", time);
    });
  }

  ngOnDestroy(): void {
    this.onDestroy$.next();
    this.onDestroy$.complete();
  }
}

unsubscribe

export class RxjsOndestroyComponent implements OnInit, OnDestroy {
  private subscription: Subscription = new Subscription();
  private timer$: Observable<number> = timer(0, 1000);

  constructor() {}

  ngOnInit(): void {
    this.subscription.add(
      this.timer$.subscribe((time) => {
        console.log("time", time);
      })
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

使用 Async Pipe

template

<div>{{ timer$ | async }}</div>

ts

export class RxjsOndestroyComponent implements OnInit, OnDestroy {
  timer$: Observable<number> = timer(0, 1000).pipe(
    tap((time: number) => console.log("time", time))
  );
}

当 component 离开时,AsyncPipe 会自动取消订阅


有限的 Observable

在 Angular 里,有一些 Observable 离开後就会自动取消订阅

里面包含了:

  • HTTP
  • router 与 ActivatedRoute
  • reactive forms 里的 valueChanges 与 statusChanges

参考资料:
Angular 中的可观察物件


<<:  Day 12 : 物件导向

>>:  [Day 23] 针对API的单元测试(三)

DAY 03 SCSS ? SASS ?

SCSS 是什麽?跟 SASS 是什麽关系? 说到这两个看起来是一样的东西,但是每次教学文章又发现好...

图的基本介绍 - DAY 19

前言 「图」就是前面所有的大集合体,并从中衍生很多的内容,内容有点超乎想像的多,容小的慢慢写~~ 有...

Day20 X CDN

CDN 这个名词在前面的篇章应该出现过蛮多次的,一直感到困惑的朋友们不用担心,今天终於要来好好介绍...

【领域展开 16 式】 认识 30% Soledad 建议安装的 plugin

人心是善变的,今天又想先看看其他东西 昨天简单换上几个设定之後,今天临机一动想要来看看前几天在安装 ...

Ubersuggest 免费 SEO 工具教学,支援中文关键字分析与内容建议

经营自媒体网站最重要的就是要让文章被看见,有了流量才有信服力,而要曝光文章最快的方法除了购买付费广告...