Scipion Scipion - 4 months ago 30
TypeScript Question

Angular2: Do we need to cancel the subscriptions to a service when it gets destroyed?

Do we need to cancel our subscriptions to a service when it gets destroyed ?

Based on the destroy event, other components that were listenning to this service can cancel their subscriptions. I just don't see why is it important to do so.

Is this a good practise, or a necessity for a performance purpose ?


Yes you do, because stuff like this can cause memory leaks. It's always a good practice to clean up after yourself to ensure that you don't run into big problems down the road, as I have in the past, especially with Angular 1.

Cleaning up after your subscriptions are fairly straightforward:

import {Subscription} from 'rxjs/Subscription';

In your class:

public configSubscription: Subscription;

Inside constructor or ngOnInit or other appropriate place:

this.configSubscription = this.api.config$.subscribe(
  config => {
    this.config = config;

Then clean up with this:

ngOnDestroy() {