DEV Community

Azriz Jasni
Azriz Jasni

Posted on • Updated on

Better way to unsubscribe in Angular


You might be wondering why do we need to unsubscribe every subscriptions. Well, you can get the answer from our friend here Netanel Basal. He have a nice .gif example so check it out.

As time goes on, we(developer) really tired of keep repeating the same process:

1. Importing ngOnDestroy,
2. Implement the interface
3. Create public function ngOnDestroy() { … }
4. Create a variables to keep list of subscriptions
5. … 
6. …
7. And repeat the whole process for other components.
Enter fullscreen mode Exit fullscreen mode

This is tedious and a waste productivity.
So, I'm going to share a 2 approach on how to unsubscribe subscription easily. But let's start with normal approach.


1. Using Inheritance

Create a BaseComponent so that, whoever extends this component are able to easily add subscription and easily unsubscribe on destroy.

And this is how to implement in component class.

One caveat tho, if the component extends BaseComponent and it also have implement ngOnDestroy() you would have to add super.ngOnDestroy();

2. Decorators

I think this approach kinda complicated a little bit as it mutate prototype. BTW i'm using mixin approach. Plus is not battle tested with this.

And here how to implement it

Thats all, feel free to play around here.

Update

  • Decorator approach with previous example it doesn't really work
  • Added once method to auto close the subscription. Can be really help full for something like click button, then trigger one http, and after that close it. (save your time to import take)
  • Added type to functions params and return
  • I'm still having difficulty with the return type in Decorator approach. Any typescripts master, please help me with this.

Discussion (0)