0
0
Angularframework~30 mins

Observable vs Promise mental model in Angular - Hands-On Comparison

Choose your learning style9 modes available
Observable vs Promise Mental Model in Angular
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use async loadUserWithPromise() with await fetchUserPromise(). Use fetchUserObservable().subscribe(user => this.userFromObservable = user) in ngOnInit().