How to cancel a subscription in Angular2

Michael Oryl picture Michael Oryl · Dec 23, 2015 · Viewed 80.9k times · Source

How does one cancel a subscription in Angular2? RxJS seems to have a dispose method, but I can't figure out how to access it. So I have code that has access to an EventEmitter and subscribes to it, like this:

var mySubscription = someEventEmitter.subscribe(
    (val) => {
        console.log('Received:', val);
    },
    (err) => {
        console.log('Received error:', err);
    },
    () => {
        console.log('Completed');
    }
);

How can I use mySubscription to cancel the subscription?

Answer

kendaleiv picture kendaleiv · Dec 23, 2015

Are you looking to unsubscribe?

mySubscription.unsubscribe();