0
0
AngularComparisonBeginner · 4 min read

Observable vs Promise in Angular: Key Differences and Usage

In Angular, Observable is a powerful way to handle multiple asynchronous values over time, while Promise handles a single asynchronous value once. Observable supports operators and cancellation, making it more flexible for complex data streams.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of Observable and Promise in Angular.

FeatureObservablePromise
Values emittedMultiple over timeSingle once
Lazy or eagerLazy (starts on subscription)Eager (starts immediately)
Cancellation supportYes (unsubscribe)No
Operators supportYes (map, filter, etc.)No
Use caseStreams, events, multiple valuesSingle async result
Angular integrationUsed in HttpClient and reactive formsLess common in Angular core
⚖️

Key Differences

Observable is a core part of Angular's reactive programming model. It can emit multiple values over time and only starts running when you subscribe to it. This makes it perfect for handling streams like user inputs, HTTP requests that emit a single response, or real-time data.

In contrast, a Promise represents a single future value. It starts immediately when created and resolves or rejects once. It cannot be cancelled or emit multiple values, which limits its flexibility in complex scenarios.

Angular's HttpClient returns Observable by default, allowing you to use operators like map and catchError to transform or handle data easily. Promises are simpler but less powerful, often used for simple async tasks outside Angular's reactive ecosystem.

⚖️

Code Comparison

This example shows how to fetch data from an API using Observable in Angular.

typescript
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-data',
  template: `<div *ngIf=\"data\">{{ data | json }}</div>`
})
export class DataComponent {
  data: any;

  constructor(private http: HttpClient) {
    this.getData().subscribe(response => {
      this.data = response;
    });
  }

  getData(): Observable<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/todos/1');
  }
}
Output
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}
↔️

Promise Equivalent

Here is how you would fetch the same data using a Promise in Angular.

typescript
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-data',
  template: `<div *ngIf=\"data\">{{ data | json }}</div>`
})
export class DataComponent {
  data: any;

  constructor(private http: HttpClient) {
    this.getData().then(response => {
      this.data = response;
    });
  }

  getData(): Promise<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/todos/1').toPromise();
  }
}
Output
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}
🎯

When to Use Which

Choose Observable when you need to handle multiple values over time, want to use powerful operators, or need to cancel ongoing operations. It fits well with Angular's reactive features like forms and HTTP.

Choose Promise for simple, one-time asynchronous tasks where you only expect a single result and do not need cancellation or streaming capabilities.

Key Takeaways

Observable handles multiple asynchronous values and supports cancellation.
Promise handles a single asynchronous value and starts immediately.
Angular favors Observable for HTTP and reactive programming.
Use Observable for streams and complex async flows.
Use Promise for simple, one-time async operations.