# 기본 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
...
}
'[DEV] Programming Lang > TypeScript' 카테고리의 다른 글
[Typescript] 개발 참고자료 목록 (0) | 2022.10.23 |
---|---|
[RxJs] debounceTime(milsec), distinctUntilChanged(), switchMap(), 실시간 검색 (0) | 2020.11.12 |
Typescript 상에서 Object에 Attribute가 존재하는지 체크하는 3가지 방법 (0) | 2020.10.23 |
[ES6] Spread(...) 문법, 비구조화 할당 문법 (0) | 2020.10.23 |
[자주쓰는표현] Partial<T>와 Object.assign(origin_json, merge_json)를 활용 (0) | 2020.09.17 |
최근댓글