Observables help your Angular component get data that changes over time. They let your component react when new data arrives or when something updates.
Observable in component lifecycle in Angular
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; @Component({ selector: 'app-example', template: `{{ data }}` }) export class ExampleComponent implements OnInit, OnDestroy { data: string = ''; private subscription!: Subscription; ngOnInit() { const observable$: Observable<string> = new Observable(observer => { observer.next('Hello from Observable!'); observer.complete(); }); this.subscription = observable$.subscribe(value => { this.data = value; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
Use subscribe() to listen to Observable data.
Always unsubscribe in ngOnDestroy() to avoid memory leaks.
this.observable$.subscribe(value => { this.data = value; });
ngOnDestroy() {
this.subscription.unsubscribe();
}interval Observable to update data every second.import { interval } from 'rxjs'; ngOnInit() { this.subscription = interval(1000).subscribe(count => { this.data = `Seconds passed: ${count}`; }); }
This component shows a timer that updates every second. It uses an Observable from interval to emit numbers every 1000 milliseconds. The component subscribes to this Observable in ngOnInit and updates the message shown. When the component is removed, it unsubscribes to stop the timer and free resources.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-timer', template: `<p>{{ message }}</p>` }) export class TimerComponent implements OnInit, OnDestroy { message: string = 'Starting timer...'; private subscription!: Subscription; ngOnInit() { const seconds$ = interval(1000); this.subscription = seconds$.subscribe(sec => { this.message = `Seconds passed: ${sec}`; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
Observables can emit multiple values over time, unlike promises which emit once.
Always unsubscribe to prevent memory leaks, especially for long-lived Observables.
Angular's async pipe can also manage subscriptions automatically in templates.
Observables let components react to changing data over time.
Subscribe in ngOnInit and unsubscribe in ngOnDestroy to manage lifecycle.
Use Observables for timers, user events, and server data streams.
Practice
ngOnInit lifecycle hook in an Angular component?Solution
Step 1: Understand
ngOnInitrolengOnInitruns once when the component is created, ideal to start tasks like subscribing to Observables.Step 2: Purpose of subscribing in
Subscribing here means the component begins listening to data streams as soon as it is ready.ngOnInitFinal Answer:
To start listening to data streams when the component is initialized -> Option AQuick Check:
Subscribe in ngOnInit = start listening [OK]
- Subscribing in ngOnDestroy instead of ngOnInit
- Expecting subscription to stop automatically
- Confusing subscription with Observable creation
ngOnDestroy lifecycle hook?Solution
Step 1: Identify the unsubscribe method
Angular subscriptions have anunsubscribe()method to stop listening to Observables.Step 2: Match method to lifecycle hook
InngOnDestroy, callingunsubscribe()properly cleans up the subscription.Final Answer:
this.subscription.unsubscribe(); -> Option AQuick Check:
Unsubscribe method = unsubscribe() [OK]
- Using subscribe() instead of unsubscribe() to stop
- Calling complete() which does not unsubscribe
- Using a non-existent destroy() method
export class TimerComponent implements OnInit, OnDestroy {
time = 0;
private subscription!: Subscription;
ngOnInit() {
this.subscription = interval(1000).subscribe(() => {
this.time++;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}What will be the value of
time after 3 seconds if the component is displayed and then removed?Solution
Step 1: Understand the interval Observable
Theinterval(1000)emits a value every 1000 milliseconds (1 second), triggering the subscription callback.Step 2: Count increments before unsubscribe
After 3 seconds, the callback runs 3 times, incrementingtimefrom 0 to 3. The unsubscribe inngOnDestroystops further increments.Final Answer:
3 -> Option BQuick Check:
3 seconds = 3 increments [OK]
- Assuming time stays 0 without increments
- Expecting error due to missing unsubscribe
- Confusing unsubscribe timing with immediate stop
export class DataComponent implements OnInit {
data$ = this.service.getData();
ngOnInit() {
this.data$.subscribe(data => {
console.log(data);
});
}
}What is the main problem here?
Solution
Step 1: Check subscription management
The code subscribes to an Observable but never unsubscribes, risking memory leaks.Step 2: Lifecycle hook missing unsubscribe
WithoutngOnDestroyto unsubscribe, the subscription stays active even after component destruction.Final Answer:
Missing unsubscribe in ngOnDestroy causes memory leak -> Option CQuick Check:
Always unsubscribe to avoid leaks [OK]
- Thinking subscription syntax is wrong
- Believing Observables can't be class properties
- Assuming ngOnInit forbids subscriptions
Solution
Step 1: Proper subscription management
Subscribing inngOnInitensures the component starts listening after creation.Step 2: Unsubscribe in
Unsubscribing cleans up resources when the component is removed, avoiding memory leaks.ngOnDestroyto prevent leaksFinal Answer:
Subscribe in ngOnInit and unsubscribe in ngOnDestroy using a Subscription object -> Option DQuick Check:
Subscribe ngOnInit + unsubscribe ngOnDestroy = safe lifecycle [OK]
- Subscribing in constructor which is too early
- Not unsubscribing and causing leaks
- Using global variables instead of Observables
Ready to prove it?
Pass the test and this pattern moves unknown
