2016-08-08 5 views
2

TypeScript를 사용하여 Angular 2 구성 요소에 새로운 rxjs Observable을 구현하려고 시도했습니다. 나는 서비스의 방법 중 하나에서 관찰을 반환 MyService, 예를 들어, ReactiveX JS 및 TypeScript - 구독 취소 방법?

export class MyService { 

    getMyObs(){ 
     return new Observable(observer => { 
      observer.next(42); 
     }); 
    } 
} 

그럼 내 코너 2 구성 요소에 내가 예를 들어,하는 OnInit이 관찰에 가입

export class MyComponent implements OnInit { 
obs: any; 

constructor(private myService: MyService){};  

    ngOnInit { 
     this.obs = myService.getMyObs().subscribe(data => { 
      // Do stuff here... 
     }); 
    }  
} 

을 만들었습니다 RxJs documentation은 관찰자가 관찰자에게 더 이상 메시지를 내 보내지 않는다는 것을 관찰 관찰자가 알 수 없도록 구독 취소하는 것에 대해 이야기합니다. 따라서, 내 구성 요소가 파괴됩니다 때 내가 관찰에서이 하다니

export class MyComponent implements OnInit, OnDestroy { 
obs: any; 

constructor(private myService: MyService){};  

    ngOnInit { 
     this.obs = myService.getMyObs().subscribe(data => { 
      // Do stuff here... 
     }); 
    } 

    ngOnDestroy { 
     this.obs.unsubscribe(); 
    } 
} 

뭔가를 탈퇴해야한다 생각 나에게 의미가 더 unsubscribe 방법이없는 말을 타이프 스크립트 컴파일러가 발생합니다 (실제로 응용 프로그램에서 발생) . 유형 정의 파일에 설명 된 메소드가없는 것으로 보입니다. TypeScript를 사용하여 관찰 대상을 올바르게 구독 취소하려면 어떻게해야합니까?

답변

0

당신은 Rxjs 모듈의 Subscription.d.ts (클래스 Subscription)에서 unsubscribe 방법의 정의를 찾을 수에 Observable. 탈퇴 방법을 추가해야합니다.

실제로 가입을 취소하고 관측 가능 항목은 구독 취소하지 마십시오.

0

먼저 다음과 같이 구독을 만듭니다.

private obs: Subscription = new Subscription(); 

그런 다음 관찰 가능으로 지정하십시오.

this.obs = myService.getMyObs().subscribe(data => { 
     if(data !== null){ 
     this.obs.unsubscribe() 
     } 
    });