0
0
Angularframework~30 mins

Unsubscribing and memory leaks in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Prevent Memory Leaks by Unsubscribing in Angular
📖 Scenario: You are building a simple Angular component that listens to a timer observable. This timer emits a number every second. To keep your app healthy, you need to stop listening when the component is removed to avoid memory leaks.
🎯 Goal: Build an Angular standalone component that subscribes to a timer observable and properly unsubscribes when the component is destroyed.
📋 What You'll Learn
Create a standalone Angular component named TimerComponent
Import CommonModule and RxJS timer function
Subscribe to a timer observable that emits every 1000 milliseconds
Store the subscription in a variable called subscription
Unsubscribe from the observable inside the ngOnDestroy lifecycle method
💡 Why This Matters
🌍 Real World
In real Angular apps, components often subscribe to data streams like user input, HTTP requests, or timers. Properly unsubscribing prevents memory leaks and keeps apps fast and responsive.
💼 Career
Understanding how to manage subscriptions and avoid memory leaks is essential for Angular developers to build reliable and maintainable applications.
Progress0 / 4 steps
1
Set up the Angular component and import timer
Create a standalone Angular component called TimerComponent. Import Component and OnDestroy from '@angular/core' and timer from 'rxjs'. Inside the component, create a public property called count initialized to 0.
Angular
Need a hint?

Remember to add standalone: true in the component decorator and import timer from 'rxjs'.

2
Create a subscription variable
Add a property called subscription of type any to hold the subscription object from the timer observable.
Angular
Need a hint?

Declare subscription as a property to store the subscription object.

3
Subscribe to the timer observable
Inside the component class, subscribe to the timer(0, 1000) observable and assign the subscription to the subscription property. Update the count property with the emitted value inside the subscription callback.
Angular
Need a hint?

Use timer(0, 1000).subscribe() and assign it to this.subscription. Update this.count inside the callback.

4
Unsubscribe in ngOnDestroy to prevent memory leaks
Implement the ngOnDestroy method. Inside it, call unsubscribe() on the subscription property to stop listening to the timer when the component is destroyed.
Angular
Need a hint?

Inside ngOnDestroy, call this.subscription.unsubscribe() to clean up.