0
0
Angularframework~30 mins

catchError for error handling in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using catchError for Error Handling in Angular
📖 Scenario: You are building a simple Angular service that fetches user data from an API. Sometimes the API might fail, so you want to handle errors gracefully.
🎯 Goal: Create an Angular service method that fetches user data and uses catchError to handle any errors by returning a friendly error message observable.
📋 What You'll Learn
Create a service method called getUserData that returns an observable
Use Angular's HttpClient to make a GET request to 'https://api.example.com/users'
Add a variable called errorMessage with the value 'Failed to load user data'
Use catchError from rxjs/operators to catch errors and return an observable of errorMessage
Ensure the service method returns the observable with error handling applied
💡 Why This Matters
🌍 Real World
Handling errors in HTTP requests is essential in real-world Angular apps to provide good user experience and avoid app crashes.
💼 Career
Knowing how to use catchError for error handling is a common requirement for Angular developers working with APIs.
Progress0 / 4 steps
1
Set up the Angular service and import HttpClient
Create an Angular service class called UserService and import HttpClient from @angular/common/http. Inject HttpClient in the constructor as private http: HttpClient.
Angular
Need a hint?

Remember to import HttpClient and inject it in the constructor for making HTTP requests.

2
Add an error message variable
Inside the UserService class, add a variable called errorMessage and set it to the string 'Failed to load user data'.
Angular
Need a hint?

Declare errorMessage as a class property with the exact string value.

3
Create getUserData method with HTTP GET request
Add a method called getUserData that returns the result of this.http.get('https://api.example.com/users').
Angular
Need a hint?

Define getUserData to return the HTTP GET observable from the URL.

4
Use catchError to handle errors in getUserData
Import catchError from rxjs/operators and of from rxjs. Update getUserData to pipe the HTTP GET observable through catchError. Inside catchError, return of(this.errorMessage) to emit the error message observable.
Angular
Need a hint?

Use pipe on the HTTP observable and inside it use catchError to return of(this.errorMessage).