Program Club

Angular 4+ ngOnDestroy () 서비스 중-Observable 제거

proclub 2020. 11. 21. 08:55
반응형

Angular 4+ ngOnDestroy () 서비스 중-Observable 제거


앵귤러 애플리케이션에서는 ngOnDestroy()컴포넌트 / 지시문에 대한 라이프 사이클 후크 있으며이 후크를 사용하여 옵저버 블 구독을 취소합니다.

@injectable()서비스 에서 생성 된 Observable을 삭제 / 삭제하고 싶습니다 . ngOnDestroy()서비스에서도 사용할 수 있다는 글을 보았습니다 .

그러나 그것은 좋은 습관이며 그렇게하는 유일한 방법이며 언제 호출됩니까? 누군가 명확히하십시오.


OnDestroy 수명주기 후크는 공급자에서 사용할 수 있습니다. 문서에 따르면 :

지시문, 파이프 또는 서비스가 파괴 될 때 호출되는 수명주기 후크입니다.

예를 들면 다음과 같습니다 .

@Injectable()
class Service implements OnDestroy {
  ngOnDestroy() {
    console.log('Service destroy')
  }
}

@Component({
  selector: 'foo',
  template: `foo`,
  providers: [Service]
})
export class Foo {
  constructor(service: Service) {}

  ngOnDestroy() {
    console.log('foo destroy')
  }
}

@Component({
  selector: 'my-app',
  template: `<foo *ngIf="isFoo"></foo>`,
})
export class App {
  isFoo = true;

  constructor() {
    setTimeout(() => {
        this.isFoo = false;
    }, 1000)
  }
}

위의 코드 Service에서 Foo컴포넌트에 속하는 인스턴스가 있으므로이 인스턴스가 소멸 될 때 소멸 될 수 있습니다 Foo.

루트 인젝터에 속한 프로 바이더의 경우 이는 애플리케이션 파괴시 발생합니다. 이는 테스트에서와 같이 여러 부트 스트랩으로 메모리 누수를 방지하는 데 도움이됩니다.

부모 인젝터의 공급자가 자식 구성 요소에 구독되면 구성 요소가 파괴 될 때 파괴되지 않습니다. 이것은 구성 요소에서 구독을 취소하는 구성 요소의 책임입니다 ngOnDestroy(다른 답변에서 설명).


서비스에서 변수 만들기

subscriptions: Subscriptions[]=[];

각 구독을 다음과 같이 어레이에 푸시하십시오.

this.subscriptions.push(...)

dispose()방법 작성

dispose(){
this.subscriptions.forEach(subscription =>subscription.unsubscribe())

ngOnDestroy 중에 컴포넌트에서이 메소드를 호출하십시오.

ngOnDestroy(){
   this.service.dispose();
 }

명확히하기 위해-폐기 할 필요가 없으며 Observables구독 만 가능합니다.

다른 사람들이 이제 ngOnDestroy서비스에서도 사용할 수 있다고 지적한 것 같습니다 . 링크 : https://angular.io/api/core/OnDestroy


takeUntil(onDestroy$)pipable 연산자에 의해 활성화 된 패턴을 선호합니다 . 이 패턴이 더 간결하고 깔끔하며 OnDestroy라이프 사이클 후크 실행시 구독을 종료하려는 의도를 명확하게 전달하는 것이 좋습니다.

이 패턴은 주입 된 Observable을 구독하는 구성 요소뿐만 아니라 서비스에도 적용됩니다. 아래의 스켈레톤 코드는 패턴을 자체 서비스에 통합하기에 충분한 세부 정보를 제공해야합니다. InjectedService... 라는 서비스를 가져오고 있다고 상상해보십시오 .

import { InjectedService } from 'where/it/lives';
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MyService implements OnDestroy {

  private onDestroy$ = new Subject<boolean>();

  constructor(
    private injectedService: InjectedService
  ) {
    // Subscribe to service, and automatically unsubscribe upon `ngOnDestroy`
    this.injectedService.observableThing().pipe(
      takeUntil(this.onDestroy$)
    ).subscribe(latestTask => {
      if (latestTask) {
        this.initializeDraftAllocations();
      }
    });
  }

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

구독 취소시기 / 방법에 대한 주제는 여기에서 광범위하게 다룹니다. Angular / RxJs 언제 구독 취소해야합니까?


토큰 사용시주의 사항

In trying to make my application as modular as possible I'll often use provider tokens to provide a service to a component. It seems that these do NOT get their ngOnDestroy methods called :-(

eg.

export const PAYMENTPANEL_SERVICE = new InjectionToken<PaymentPanelService>('PAYMENTPANEL_SERVICE');

With a provider section in a component:

 {
     provide: PAYMENTPANEL_SERVICE,
     useExisting: ShopPaymentPanelService
 }

My ShopPaymentPanelService does NOT have its ngOnDestroy method called when the component is disposed. I just found this out the hard way!

A workaround is to provide the service in conjunction with useExisting.

[
   ShopPaymentPanelService,

   {
       provide: PAYMENTPANEL_SERVICE,
       useExisting: ShopPaymentPanelService
   }
]

When I did this the ngOnDispose was called as expected.

Not sure if this is a bug or not but very unexpected.

참고URL : https://stackoverflow.com/questions/45898948/angular-4-ngondestroy-in-service-destroy-observable

반응형