# 기본 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

  ...

}

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기