Unsubscribing from observables
There are some known techniques to use when we are concerned with cleaning up resources from observables:
- Unsubscribe from observables manually.
- Use the
async
pipe.
Let's see both techniques in action in the following sections.
Destroying a component
A component has life cycle events that we can hook on them and perform custom logic, as we learned in Chapter 3, Component Interaction and Inter-Communication. One of them is the ngOnDestroy
event, which is called when the component is destroyed and no longer exists.
Recall HeroListComponent
, which we used earlier in our examples. It subscribes to the getHeroes
method of HeroService
upon component initialization. When the component is destroyed, the reference of the subscription seems to stay active, which may lead to unpredictable behavior.
Important Note
Luckily for us, it is not. The getHeroes
method is handled internally by HttpClient
, which takes care of all cleanup...