How to avoid memory leak from Observable subscriprions wihtin a Service in Angular?

Viewed 48

I am used to unsubscribing from Ovservable subscriptions on the ngOnDestroy Hook when I subscribe to an observable within a component. But the problem is when I subscribe from within a Service where there is no such thing as "On Destroy" since the service lives as long as the app is running.

How Do I avoid the memory leak in this case?

1 Answers

According to the docs for OnDestroy, services can implement OnDestroy.

A lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.

Like components, this is typically where you would unsubscribe from observables.

Related