昨天说到了将资料订阅出来渲染在页面上的事,那麽就就来说说 RxJs 解订阅这件事吧。
这也是为了避免 memory leak,或重覆订阅所造成的 BUG,若非有限订阅,通常在订阅离开後,都需要解订阅。
只执行第一次,通常用於第一次进来读取成功取得资料後,就不需再次执行
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;
});
}
}
只发生一次
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;
});
}
}
持续执行,直到离开
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();
}
}
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();
}
}
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 会自动取消订阅
在 Angular 里,有一些 Observable 离开後就会自动取消订阅
里面包含了:
参考资料:
Angular 中的可观察物件
SCSS 是什麽?跟 SASS 是什麽关系? 说到这两个看起来是一样的东西,但是每次教学文章又发现好...
前言 「图」就是前面所有的大集合体,并从中衍生很多的内容,内容有点超乎想像的多,容小的慢慢写~~ 有...
CDN 这个名词在前面的篇章应该出现过蛮多次的,一直感到困惑的朋友们不用担心,今天终於要来好好介绍...
人心是善变的,今天又想先看看其他东西 昨天简单换上几个设定之後,今天临机一动想要来看看前几天在安装 ...
经营自媒体网站最重要的就是要让文章被看见,有了流量才有信服力,而要曝光文章最快的方法除了购买付费广告...