📖 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
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
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
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
Hint
Inside ngOnDestroy, call this.subscription.unsubscribe() to clean up.
Practice
(1/5)
1. Why is it important to unsubscribe from Observables in Angular components?
easy
A. To make the component load faster initially.
B. To prevent memory leaks by stopping ongoing subscriptions when the component is destroyed.
C. To increase the number of active subscriptions.
D. To automatically refresh the component view.
Solution
Step 1: Understand Observable subscriptions
Subscriptions keep listening to data streams, even if the component is gone.
Step 2: Recognize the effect of not unsubscribing
Not unsubscribing causes memory to be used unnecessarily, leading to leaks.
Final Answer:
To prevent memory leaks by stopping ongoing subscriptions when the component is destroyed. -> Option B
Quick Check:
Unsubscribe to avoid memory leaks = B [OK]
Hint: Unsubscribe in ngOnDestroy to avoid leaks [OK]
Common Mistakes:
Thinking Angular unsubscribes automatically
Believing unsubscribing improves load speed
Ignoring memory leaks from active subscriptions
2. Which of the following is the correct way to unsubscribe from a subscription in Angular's ngOnDestroy method?
easy
A. this.subscription.unsubscribe();
B. this.subscription.stop();
C. this.subscription.close();
D. this.subscription.cancel();
Solution
Step 1: Recall Subscription API
The Subscription object has an unsubscribe() method to stop listening.
Step 2: Identify correct method name
Only unsubscribe() is valid; others do not exist on Subscription.
Final Answer:
this.subscription.unsubscribe(); -> Option A
Quick Check:
Use unsubscribe() to stop subscription = D [OK]
Hint: Use unsubscribe() method to stop subscriptions [OK]
Common Mistakes:
Using non-existent methods like stop() or cancel()
Forgetting to call unsubscribe() at all
Calling unsubscribe() outside ngOnDestroy
3. Consider this Angular component snippet:
export class MyComponent implements OnDestroy {
private sub = this.service.getData().subscribe(data => console.log(data));
ngOnDestroy() {
// missing unsubscribe
}
}
What will happen if this component is created and destroyed multiple times without adding unsubscribe in ngOnDestroy?
medium
A. Memory usage will increase over time due to active subscriptions not being cleaned up.
B. The component will automatically unsubscribe, so no issues occur.
C. The subscription will throw an error immediately on component destroy.
D. The component will reload data only once and then stop.
Solution
Step 1: Analyze missing unsubscribe
Without calling unsubscribe, the subscription stays active even after component destruction.
Step 2: Understand consequences
Repeated creation and destruction cause multiple active subscriptions, increasing memory use.
Final Answer:
Memory usage will increase over time due to active subscriptions not being cleaned up. -> Option A
Quick Check:
Missing unsubscribe causes memory leaks = A [OK]
Hint: No unsubscribe means memory leaks grow with component reuse [OK]
Common Mistakes:
Assuming Angular auto-unsubscribes
Expecting errors on destroy without unsubscribe
Thinking subscription stops automatically
4. Identify the problem in this Angular component code related to unsubscribing: