0
0
Angularframework~30 mins

Observable in component lifecycle in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Observable in component lifecycle
📖 Scenario: You are building a simple Angular component that listens to a timer observable. This timer emits a number every second. You want to show the current timer value in the component and clean up the subscription when the component is destroyed.
🎯 Goal: Create an Angular standalone component that subscribes to a timer observable on initialization, updates a displayed counter, and unsubscribes when the component is destroyed.
📋 What You'll Learn
Create a standalone Angular component named TimerComponent
Use Angular's timer observable from rxjs that emits every 1000 milliseconds
Subscribe to the timer observable inside the component lifecycle
Store the emitted value in a component property named count
Unsubscribe from the observable when the component is destroyed to avoid memory leaks
Display the current count value in the component template
💡 Why This Matters
🌍 Real World
Timers and observables are common in Angular apps for live updates, animations, or polling data.
💼 Career
Understanding observables and component lifecycle is essential for Angular developers to manage data streams and resource cleanup properly.
Progress0 / 4 steps
1
Set up the Angular component and import timer
Create a standalone Angular component named TimerComponent. Import Component from @angular/core and timer from rxjs. Initialize a public property count with 0.
Angular
Need a hint?

Start by importing Component and timer. Then create a standalone component with a count property set to 0.

2
Create a subscription property and timer observable
Inside TimerComponent, create a private property named subscription to hold the subscription. Create a timer observable named timer$ that emits every 1000 milliseconds using timer(0, 1000).
Angular
Need a hint?

Add a private property subscription to store the subscription. Create timer$ using timer(0, 1000) to emit immediately and then every second.

3
Subscribe to the timer observable and update count
In the ngOnInit() lifecycle method, subscribe to timer$. Update the count property with the emitted value inside the subscription callback.
Angular
Need a hint?

Implement ngOnInit(). Inside it, subscribe to timer$ and update count with the emitted value.

4
Unsubscribe from timer observable on component destroy
Implement the ngOnDestroy() lifecycle method. Inside it, unsubscribe from subscription to clean up the observable subscription.
Angular
Need a hint?

Implement ngOnDestroy() and call unsubscribe() on subscription to avoid memory leaks.