Unsubscribing from Angular HttpClient data requests observables
Intro
Just recently, in one of my Angular applications, I decided to to use HttpClient
data-request functions nearly directly in the components. This application is very simple: only a couple of components and services bid together to communicate with an API. That's why I decided not to build any fancy state management mechanism, but simply provide services that are acting as data-providers, and make use of those services directly in the components.
Case of unsubscribing
While subscribing on data providing observables directly in the components, I started wondering about unsubscribing of those once the component will get destroyed in the applications lifecycle.
Unsubscribing from the observables in the ngOnDestroy
lifecycle phase is a good practice, not only because it helps to avoid memory leaks in your application, but also long-living subscriptions may influence your app's logic.
After a bit of thinking and googling around, it turned out that there is no need to unsubscribe for the observables that come from the HttpClient
data providing methods (i.e.. .get()
) as those observables are finite.
A finite observable is the one that completes.
That means that after emitting the first value of…