ngOnDestroy in services - unsubscribe to avoid memory leaks in SSR Angular 💧

krisplatis

Krzysztof Platis

Posted on April 20, 2021

ngOnDestroy in services - unsubscribe to avoid memory leaks in SSR Angular 💧

I believed that I don’t need to unsubscribe RxJs subscriptions created in Angular singleton services, but only in components. I changed my mind when saw memory leaks in SSR (Angular Universal).

One NodeJS process, but many rendered apps

The NodeJS process of the SSR server on every http request: bootstraps a fresh Angular app, sends the output HTML to the client, and destroys the app. This cycle is repeated for each request inside one shared long-living NodeJS process. So any pending subscription created in any app’s service survives even after the app is destroyed. And it causes memory leaks in the server.

Unsubscribe in services’ ngOnDestroy

Angular invokes in SSR the lifecycle method ngOnDestroy not only for components, but also for every service, when the app is destroyed. Therefore it’s a good place to unsubscribe any pending subscriptions created by the service.

If you really feel like buying me a coffee

... then feel free to do it. Many thanks! 🙌

Buy Me A Coffee

💖 💪 🙅 🚩
krisplatis
Krzysztof Platis

Posted on April 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related