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.
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.
And here how to implement it
Thats all, feel free to play around here.
Discussion (0)