What is the difference between Observable and Promise in Angular?
const promise = fetch('/api/users').then(r => r.json());
// Starts immediately, resolves once
import { Observable, interval } from 'rxjs';
import { map, take } from 'rxjs/operators';
// Emits 0,1,2,3,4 then completes
const five$ = interval(1000).pipe(take(5));
// Lazy — nothing happens yet
const sub = five$.subscribe(val => console.log(val));
// Cancel anytime
sub.unsubscribe();
// Returns Observable — subscribe to execute the request
this.http.get('/api/users').pipe(
map(users => users.filter(u => u.active)),
catchError(err => EMPTY),
).subscribe(users => this.users = users);
// Convert to Promise when needed
const users = await firstValueFrom(this.http.get('/api/users'));
| Scenario | Use |
|---|---|
| Single HTTP request | Either (Observable preferred in Angular) |
| Real-time/streaming data | Observable |
| Event streams | Observable |
| Simple async with async/await | Promise (via firstValueFrom) |
All Comments