5

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 Answers 3

4

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

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

  return () => {
    console.log('unsubscribe')
  }
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

Can we do it also in Angular 8?
1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.