Bird
Raised Fist0
Angularframework~5 mins

Observable vs Promise mental model in Angular

Choose your learning style10 modes available
Introduction

Observables and Promises help us handle data that comes later, like waiting for a message or a file. They let us work with things that take time without stopping everything.

When you want to get one value once, like loading user info from a server.
When you want to get many values over time, like live chat messages or sensor data.
When you want to cancel waiting for data if you don't need it anymore.
When you want to handle data streams that can start and stop anytime.
When you want to combine or transform multiple data sources easily.
Syntax
Angular
Promise example:
const promise = new Promise((resolve, reject) => {
  // do something async
  resolve('done');
});
promise.then(value => console.log(value));

Observable example:
import { Observable } from 'rxjs';
const observable = new Observable(subscriber => {
  subscriber.next('first');
  subscriber.next('second');
  subscriber.complete();
});
observable.subscribe(value => console.log(value));

Promises handle one value or error and then finish.

Observables can send many values over time and can be stopped.

Examples
This Promise waits 1 second then sends one message.
Angular
const promise = new Promise(resolve => {
  setTimeout(() => resolve('Hello from Promise!'), 1000);
});
promise.then(msg => console.log(msg));
This Observable sends two messages over time and then finishes.
Angular
import { Observable } from 'rxjs';
const observable = new Observable(subscriber => {
  subscriber.next('First message');
  setTimeout(() => subscriber.next('Second message'), 1000);
  setTimeout(() => subscriber.complete(), 1500);
});
observable.subscribe({
  next: msg => console.log(msg),
  complete: () => console.log('Done')
});
Promise example fetching data once from a server.
Angular
const promise = fetch('https://api.example.com/data').then(res => res.json());
promise.then(data => console.log(data));
Observable example emitting numbers every second, stopped after 3.5 seconds.
Angular
import { interval } from 'rxjs';
const observable = interval(1000); // emits numbers every second
const subscription = observable.subscribe(num => console.log(num));
setTimeout(() => subscription.unsubscribe(), 3500);
Sample Program

This Angular component shows how a Promise gives one message after 2 seconds, while an Observable sends multiple messages over time and then finishes.

Angular
import { Component } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <h1>Observable vs Promise Demo</h1>
    <button (click)="startPromise()">Start Promise</button>
    <button (click)="startObservable()">Start Observable</button>
    <div>
      <h2>Promise Result:</h2>
      <p>{{ promiseResult }}</p>
    </div>
    <div>
      <h2>Observable Results:</h2>
      <ul>
        <li *ngFor="let msg of observableResults">{{ msg }}</li>
      </ul>
    </div>
  `
})
export class AppComponent {
  promiseResult = '';
  observableResults: string[] = [];
  private observableSubscription: any;

  startPromise() {
    this.promiseResult = 'Waiting...';
    const promise = new Promise<string>(resolve => {
      setTimeout(() => resolve('Promise says hello!'), 2000);
    });
    promise.then(msg => this.promiseResult = msg);
  }

  startObservable() {
    this.observableResults = [];
    const observable = new Observable<string>(subscriber => {
      subscriber.next('Observable message 1');
      setTimeout(() => subscriber.next('Observable message 2'), 1000);
      setTimeout(() => subscriber.next('Observable message 3'), 2000);
      setTimeout(() => subscriber.complete(), 2500);
    });

    this.observableSubscription = observable.subscribe({
      next: msg => this.observableResults.push(msg),
      complete: () => this.observableResults.push('Observable complete')
    });
  }
}
OutputSuccess
Important Notes

Promises start immediately when created; Observables start when you subscribe.

Observables can be cancelled by unsubscribing; Promises cannot be cancelled once started.

Use Observables for streams of data, Promises for single async results.

Summary

Promises handle one future value or error.

Observables handle many values over time and can be stopped.

Choose based on whether you expect one or many results and if you need to cancel.

Practice

(1/5)
1. Which statement best describes the difference between an Observable and a Promise in Angular?
easy
A. Observable is synchronous; Promise is asynchronous.
B. Promise handles a single future value; Observable can handle multiple values over time.
C. Promise can be cancelled; Observable cannot be cancelled.
D. Observable handles a single future value; Promise can handle multiple values over time.

Solution

  1. Step 1: Understand the nature of Promise

    A Promise represents a single future value or error that will be resolved once.
  2. Step 2: Understand the nature of Observable

    An Observable can emit multiple values over time and can be stopped or cancelled.
  3. Final Answer:

    Promise handles a single future value; Observable can handle multiple values over time. -> Option B
  4. Quick Check:

    Promise = single value, Observable = multiple values [OK]
Hint: Promise = one value, Observable = many values over time [OK]
Common Mistakes:
  • Thinking Promise can emit multiple values
  • Believing Observable cannot be cancelled
  • Confusing synchronous and asynchronous behavior
2. Which of the following is the correct way to create a Promise that resolves with the value 42 in Angular?
easy
A. const p = new Promise((resolve, reject) => reject(42));
B. const p = new Promise(resolve => reject(42));
C. const p = new Promise((resolve, reject) => resolve(42));
D. const p = new Promise(() => 42);

Solution

  1. Step 1: Check Promise constructor syntax

    The Promise constructor takes a function with two parameters: resolve and reject.
  2. Step 2: Verify correct usage to resolve with 42

    Calling resolve(42) inside the function correctly resolves the Promise with 42.
  3. Final Answer:

    const p = new Promise((resolve, reject) => resolve(42)); -> Option C
  4. Quick Check:

    Promise constructor needs resolve and reject parameters [OK]
Hint: Promise constructor needs (resolve, reject) parameters [OK]
Common Mistakes:
  • Omitting reject parameter in Promise constructor
  • Calling reject instead of resolve to return value
  • Returning value directly without resolve
3. Consider this Angular code snippet:
const obs = new Observable(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.complete();
});

obs.subscribe(value => console.log(value));

What will be printed to the console?
medium
A. 1 2
B. 1
C. 2
D. No output

Solution

  1. Step 1: Analyze Observable emissions

    The Observable emits two values: 1 and 2, then completes.
  2. Step 2: Understand subscription behavior

    The subscriber logs each emitted value, so both 1 and 2 are printed.
  3. Final Answer:

    1 2 -> Option A
  4. Quick Check:

    Observable emits multiple values, all logged [OK]
Hint: Observable emits all next() values until complete [OK]
Common Mistakes:
  • Assuming only first value is logged
  • Thinking complete() emits a value
  • Confusing Observable with Promise single value
4. What is wrong with this Promise usage in Angular?
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});
p.then(result => console.log(result));
p.catch(error => console.error(error));
p.cancel();
medium
A. Promises do not have a cancel() method, so calling it causes an error.
B. The Promise should use reject() instead of resolve() inside setTimeout.
C. The then() method should come after catch(), not before.
D. The Promise constructor is missing the reject parameter.

Solution

  1. Step 1: Check Promise API for cancellation

    Promises do not support cancellation; there is no cancel() method.
  2. Step 2: Identify error cause

    Calling p.cancel() will cause a runtime error because cancel() is undefined.
  3. Final Answer:

    Promises do not have a cancel() method, so calling it causes an error. -> Option A
  4. Quick Check:

    Promise cancellation is not supported [OK]
Hint: Promises cannot be cancelled; no cancel() method exists [OK]
Common Mistakes:
  • Thinking Promise supports cancel() like Observable
  • Confusing resolve and reject usage
  • Believing then() must come after catch()
5. You want to fetch user data that updates every 5 seconds and be able to stop the updates when the user navigates away. Which approach fits best in Angular?
hard
A. Use an Observable but do not unsubscribe; it stops automatically.
B. Use a Promise that resolves with user data every 5 seconds.
C. Use a Promise and call cancel() to stop fetching data.
D. Use an Observable that emits new user data every 5 seconds and unsubscribe on navigation.

Solution

  1. Step 1: Identify need for multiple values over time

    Fetching user data every 5 seconds means multiple values over time, which suits an Observable.
  2. Step 2: Understand cancellation requirement

    Observables can be unsubscribed to stop receiving updates, fitting the need to stop on navigation.
  3. Final Answer:

    Use an Observable that emits new user data every 5 seconds and unsubscribe on navigation. -> Option D
  4. Quick Check:

    Multiple updates + cancel = Observable with unsubscribe [OK]
Hint: Multiple updates + cancel = Observable with unsubscribe [OK]
Common Mistakes:
  • Using Promise for multiple repeated values
  • Assuming Promise supports cancel()
  • Not unsubscribing Observable causing memory leaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard