📖 Scenario: You are building a simple Angular app that fetches user data from a server. You want to understand the difference between Observable and Promise by creating examples of both and seeing how they behave.
🎯 Goal: Create an Angular component that uses both a Promise and an Observable to fetch user data. Observe how each handles the data and how you subscribe or await the results.
📋 What You'll Learn
Create a user data object with exact values
Add a configuration variable to simulate delay
Use a Promise to fetch the user data with delay
Use an Observable to fetch the user data with delay
Subscribe to the Observable and handle the Promise with async/await
Display the fetched user data in the component template
💡 Why This Matters
🌍 Real World
Understanding how to fetch data asynchronously in Angular apps using Promises and Observables is essential for building responsive user interfaces that handle server data smoothly.
💼 Career
Many Angular developer roles require knowledge of Observables and Promises to manage data streams and asynchronous operations effectively.
Progress0 / 4 steps
1
Create the user data object
Create a constant called userData with the exact object: { id: 1, name: 'Alice', age: 30 }
Angular
Hint
Use const userData = { id: 1, name: 'Alice', age: 30 }; to create the object.
2
Add a delay configuration variable
Add a constant called delayMs and set it to 1000 to simulate a 1 second delay
Angular
Hint
Use const delayMs = 1000; to set the delay.
3
Create Promise and Observable to fetch user data
Create a function called fetchUserPromise that returns a Promise resolving userData after delayMs milliseconds. Also create a function called fetchUserObservable that returns an Observable emitting userData after delayMs milliseconds using of and delay from rxjs.
Angular
Hint
Use new Promise(resolve => setTimeout(() => resolve(userData), delayMs)) for the Promise. Use of(userData).pipe(delay(delayMs)) for the Observable.
4
Use Promise and Observable in Angular component
In an Angular component, create a property userFromPromise and assign it the awaited result of fetchUserPromise() inside an async function called loadUserWithPromise. Also create a property userFromObservable and subscribe to fetchUserObservable() to assign the emitted value. Call both methods in ngOnInit. Display both user data objects in the template.
Angular
Hint
Use async loadUserWithPromise() with await fetchUserPromise(). Use fetchUserObservable().subscribe(user => this.userFromObservable = user) in ngOnInit().
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
Step 1: Understand the nature of Promise
A Promise represents a single future value or error that will be resolved once.
Step 2: Understand the nature of Observable
An Observable can emit multiple values over time and can be stopped or cancelled.
Final Answer:
Promise handles a single future value; Observable can handle multiple values over time. -> Option B
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
Step 1: Check Promise constructor syntax
The Promise constructor takes a function with two parameters: resolve and reject.
Step 2: Verify correct usage to resolve with 42
Calling resolve(42) inside the function correctly resolves the Promise with 42.
Final Answer:
const p = new Promise((resolve, reject) => resolve(42)); -> Option C
Quick Check:
Promise constructor needs resolve and reject parameters [OK]
The Observable emits two values: 1 and 2, then completes.
Step 2: Understand subscription behavior
The subscriber logs each emitted value, so both 1 and 2 are printed.
Final Answer:
1 2 -> Option A
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
Step 1: Check Promise API for cancellation
Promises do not support cancellation; there is no cancel() method.
Step 2: Identify error cause
Calling p.cancel() will cause a runtime error because cancel() is undefined.
Final Answer:
Promises do not have a cancel() method, so calling it causes an error. -> Option A
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
Step 1: Identify need for multiple values over time
Fetching user data every 5 seconds means multiple values over time, which suits an Observable.
Step 2: Understand cancellation requirement
Observables can be unsubscribed to stop receiving updates, fitting the need to stop on navigation.
Final Answer:
Use an Observable that emits new user data every 5 seconds and unsubscribe on navigation. -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.