Angular: Automatically Unsubscribe Observables on Destroy

Don’t ever write another ngOnDestroy to clean your subscriptions

Lucas Paganini
2 min readJun 3, 2022

See this and many other articles at lucaspaganini.com

One thing that really annoys me when working with Angular is having to save all my subscriptions just to unsubscribe from them on ngOnDestroy.

It’s just so annoying, I have to do this everywhere. I’ve searched for solutions but all of them involve declaring ngOnDestroy, and I don't want that.

I just want to subscribe to something and tell Angular to automatically unsubscribe when the component is destroyed.

I’ve realized, however, that I can achieve what I want by delegating ngOnDestroy to a service, which makes me so excited! This has been a pain point for me since Angular 2 was released.

Service per Component

By providing a service in a component, its existence becomes dependent on the component.

When the component is destroyed, the service is destroyed too. I’ll show you:

Provide service in your component, inject it in the constructor and log when ngOnDestroy() happens in the service and the component.

You’ll see that the service is destroyed right before the component.

Until the Service Destroys

Knowing that we can create an observable that emits when the service is destroyed and use takeUntil() to automatically unsubscribe when that happens.

To simplify, we can put the takeUntil() logic in our service and expose it through a simple method.

I’ve added this to my Angular utilities library. If you don’t want to write anything, you can just install the library. npm i @lucaspaganini/angular-utils

Conclusion

What do you think? Loved it? Hated it? Has a better solution? Let me know what you think on my Twitter. Have a great day, and I’ll see you soon!

References

  1. angular-ultils Library npm
  2. Repository angular-utils GitHub

--

--

Lucas Paganini

Founder and CEO at Unvoid • Host "Adventures in Angular" • Helping companies to develop high quality software with the Angular framework