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.