5
votes

I've been attempting to implement a new rxjs Observable in an Angular 2 component using TypeScript. I have created a service, MyService that returns an observable in one of its methods, e.g.,

export class MyService {

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

Then in my Angular 2 component I subscribe to this observable in OnInit, e.g.,

export class MyComponent implements OnInit {
obs: any;

constructor(private myService: MyService){};    

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

The RxJs documentation talks about unsubscribing from your observable such that your observable knows to no longer emit messages to your observer. Therefore, I figured I should be unsubscribing from the observable when my component gets destroyed, something like

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();
    }  
}

Whilst this makes sense to me, the typescript compiler throws (and indeed the application throws) saying there is no unsubscribe method. There appears to be no such method described in the type definition files. How do I correctly unsubscribe from an observable using TypeScript?

3

3 Answers

4
votes

You need add unsubscribe method to your Observable., Disposing Observable Executions

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

  return () => {
    console.log('unsubscribe')
  }
}); 
1
votes

First create Subscription as follow.

private obs: Subscription = new Subscription();

Then assign to observable.

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

You can find the definition of the unsubscribe method in the Subscription.d.ts (class Subscription) of the Rxjs module.

As a matter of fact, you unsubscribe a subscription and not an observable.