# 기본 Observable unSubscribe() 방식
import {OnDestroy} from '@angular/core';
import {Subscription} from 'rxjs';
export class AutoUnsubscribeComponent implements OnDestroy {
protected subscriptions: Subscription[] = [];
public ngOnDestroy(): void {
for (const subscription of this.subscriptions) {
subscription.unsubscribe();
}
}
protected addSubscriptions(...subs: Subscription[]) {
this.subscriptions.push(...subs);
}
}
# UntilDestroy 어노테이션 방식 (ng-neat 라이브러리 필요)
@UntilDestroy()
@Component(...)
export class MyComponent implements OnInit {
...
public ngOnInit() {
this.userService.getUser()
.pipe(untilDestroyed(this))
.subscribe();
}
// ngOnDestroy is not needed here (Angular 9+ only)!
// 8버전보다 밑일 경우, ngOnDestroy 선언해주어야 함
}
# AuthUnsubscribe 어노테이션 방식 (ngx-auto-unsubscribe 라이브러리 필요)
@AutoUnsubscribe()
@Component(...)
export class MyComponent implements OnDestroy, OnInit {
protected addressSubscription: Subscription;
protected userSubscription: Subscription;
...
public ngOnInit() {
this.addressSubscription = // subscribe here or wherever else
this.userSubscription = // subscribe here or wherever else
}
public ngOnDestroy() {} // must be present
...
}
'개발 일반 > 프로그래밍 언어 ∕ JS & TS' 카테고리의 다른 글
[Typescript] 개발 참고자료 목록 (0) | 2022.10.23 |
---|---|
[RxJs] debounceTime(milsec), distinctUntilChanged(), switchMap(), 실시간 검색 (0) | 2020.11.12 |
Promise와 Observable 객체의 차이 (0) | 2020.10.28 |
Promise, Async Await에 대한 고찰 (0) | 2020.10.28 |
Typescript 상에서 Object에 Attribute가 존재하는지 체크하는 3가지 방법 (0) | 2020.10.23 |
최근댓글