📖 Scenario: You are building a simple Angular app that fetches user data from a server. Sometimes the server might return an error, like a 404 or 500. You want to handle these HTTP errors gracefully so the app can show a friendly message instead of crashing.
🎯 Goal: Create an Angular standalone component that fetches user data using HttpClient. Add error handling to catch HTTP errors and store an error message in a signal. Display the error message in the template if an error occurs.
📋 What You'll Learn
Use Angular 17+ standalone component with signals
Inject HttpClient using inject()
Create a signal to hold the user data
Create a signal to hold the error message
Use HttpClient.get() to fetch data from 'https://jsonplaceholder.typicode.com/users/1'
Use subscribe() with error callback to handle HTTP errors
Display user name if data loads successfully
Display error message if an error occurs
💡 Why This Matters
🌍 Real World
Handling HTTP errors is essential in real apps to provide good user experience and avoid crashes when servers fail or data is missing.
💼 Career
Knowing how to handle HTTP errors in Angular is a key skill for frontend developers working with APIs and building robust web applications.
Progress0 / 4 steps
1
DATA SETUP: Create a standalone Angular component with signals
Create a standalone Angular component called UserComponent. Inside it, create two signals: user initialized to null and errorMessage initialized to an empty string ''. Import necessary Angular modules and functions.
Angular
Hint
Use signal(null) for user and signal('') for errorMessage.
2
CONFIGURATION: Inject HttpClient to make HTTP requests
Import HttpClientModule and HttpClient from @angular/common/http. Add HttpClientModule to the component's imports array. Inside the component class, create a private variable http by calling inject(HttpClient).
Angular
Hint
Remember to add HttpClientModule to imports and use inject(HttpClient) inside the class.
3
CORE LOGIC: Fetch user data and handle HTTP errors
Inside the UserComponent constructor, use this.http.get() to fetch data from 'https://jsonplaceholder.typicode.com/users/1'. Subscribe to the observable. In the success callback, update the user signal with the response. In the error callback, update the errorMessage signal with the string 'Failed to load user data.'.
Angular
Hint
Use subscribe with next and error callbacks to update signals.
4
COMPLETION: Display user name or error message in the template
Update the component's template to show the user's name if user() is not null. If errorMessage() is not empty, display the error message inside a <div> with role="alert" for accessibility.
Angular
Hint
Use Angular's *ngIf to conditionally show user name or error message. Add role="alert" for accessibility on the error message.
Practice
(1/5)
1. What is the main purpose of using catchError in Angular HTTP requests?
easy
A. To handle errors that occur during the HTTP request
B. To retry the HTTP request automatically
C. To transform the HTTP response data
D. To cancel the HTTP request
Solution
Step 1: Understand the role of catchError
catchError is used to catch errors in an observable stream, such as HTTP requests.
Step 2: Identify its purpose in HTTP requests
It allows handling errors gracefully instead of letting them crash the app or go unhandled.
Final Answer:
To handle errors that occur during the HTTP request -> Option A
Quick Check:
catchError handles HTTP errors = A [OK]
Hint: Remember catchError catches errors in observable streams [OK]
A. throwError should be called with a function: throwError(() => error)
B. catchError should be outside pipe()
C. subscribe should be before pipe()
D. console.log cannot be used inside catchError
Solution
Step 1: Check throwError usage
In RxJS 7+, throwError requires a function returning the error: throwError(() => error).
Step 2: Verify catchError and subscribe placement
catchError must be inside pipe(), and subscribe after pipe(), which is correct here.
Final Answer:
throwError should be called with a function: throwError(() => error) -> Option A
Quick Check:
throwError needs function wrapper = D [OK]
Hint: Use throwError(() => error) to avoid RxJS errors [OK]
Common Mistakes:
Calling throwError directly with error object
Placing catchError outside pipe()
Misordering subscribe and pipe()
5. You want to show a friendly message to users when an HTTP error occurs, but still log the original error for debugging. Which code snippet correctly implements this in Angular?
hard
A. return this.http.get(url).pipe(catchError(err => { console.error(err); return of('Error occurred'); }))
B. return this.http.get(url).pipe(catchError(err => { return throwError(() => new Error('Error occurred')); }))
return this.http.get(url).pipe(catchError(err => { alert('Error occurred'); console.error(err); return throwError(() => err); })) shows an alert to users and logs the error to console, fulfilling both requirements.
Step 2: Verify error propagation
It returns throwError(() => err) to pass the error downstream for further handling.