Angular API Response Handling
Learn how Angular handles successful API responses, errors, completion events, loading states and typed HTTP responses when working with REST APIs.
What is API Response Handling?
When Angular sends an HTTP request, the backend returns a response. The application must handle that response correctly before updating the user interface.
Response handling allows the application to manage success responses, errors and completion.
Angular HttpClient returns an Observable, so the response can be processed inside the subscription.
API Response Flow
Types of API Responses
Success
The API request completed successfully and returned data.
Error
The API request failed and an error response was returned.
Complete
The Observable completed after processing the response.
Loading
The UI can display a loading state while the request is running.
Handling API Response with subscribe()
The subscribe() method can be used to handle the emitted API response.
this.courseService
.getCourses()
.subscribe({
next: courses => {
console.log(
'Courses:',
courses
);
},
error: error => {
console.error(error);
},
complete: () => {
console.log(
'Request completed'
);
}
});
1. next Callback
The next callback receives the successful response emitted by the Observable.
It is commonly used to store returned data and update the UI.
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
}
});
API Response
Courses received successfully.
The returned data can now be displayed in the Angular template.
2. error Callback
The error callback is executed when the HTTP request fails.
Angular applications should handle errors and provide a meaningful message instead of leaving the user without feedback.
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
this.errorMessage =
'Unable to load courses.';
console.error(error);
}
});
3. complete Callback
The complete callback runs when the Observable finishes successfully without an error.
It can be useful for logging or completing UI-related processing.
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
console.error(error);
},
complete: () => {
console.log(
'API operation completed'
);
}
});
Handling Loading State
A loading flag can be used to inform the user that the API request is currently in progress.
loading = false;
courses: Course[] = [];
errorMessage = '';
loadCourses() {
this.loading = true;
this.errorMessage = '';
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
console.error(error);
this.errorMessage =
'Unable to load courses.';
this.loading = false;
},
complete: () => {
this.loading = false;
}
});
}
Working with HttpErrorResponse
Angular provides information about a failed HTTP request through HttpErrorResponse.
Properties such as the HTTP status code and error information can help the application decide how to respond.
import {
HttpErrorResponse
} from '@angular/common/http';
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: (
error: HttpErrorResponse
) => {
console.error(
'Status:',
error.status
);
console.error(
'Message:',
error.message
);
}
});
Common HTTP Status Codes
| Status | Meaning | Example |
|---|---|---|
| 200 | Request completed successfully. | GET request returns courses. |
| 201 | Resource created successfully. | POST creates a course. |
| 400 | Invalid request data. | Validation problem. |
| 401 | Authentication is required or failed. | User is not authenticated. |
| 403 | Access is not permitted. | User does not have required permission. |
| 404 | Requested resource was not found. | Invalid course ID. |
| 500 | Server-side error. | Backend processing failure. |
Displaying Error Messages
errorMessage = '';
loadCourses() {
this.errorMessage = '';
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
if (error.status === 404) {
this.errorMessage =
'Courses were not found.';
}
else if (error.status === 500) {
this.errorMessage =
'Server error occurred.';
}
else {
this.errorMessage =
'Unable to load courses.';
}
}
});
}
@if (errorMessage) {
<div class="alert alert-danger">
{{ errorMessage }}
</div>
}
Reading Response Data
The response body contains the data returned by the backend. A TypeScript type can be used to describe the expected response.
interface Course {
id: number;
name: string;
duration: string;
fees: number;
}
getCourses() {
return this.http.get<Course[]>(
this.apiUrl
);
}
Response Example
ID: 101
Course: .NET Full Stack
Duration: 6 Months
Fees: ₹35000
Complete Response Handling Example
courses: Course[] = [];
loading = false;
errorMessage = '';
loadCourses() {
this.loading = true;
this.errorMessage = '';
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
console.error(error);
this.errorMessage =
'Failed to load courses.';
this.loading = false;
},
complete: () => {
this.loading = false;
console.log(
'Request completed'
);
}
});
}
Handling Create Response
addCourse(course: Course) {
this.courseService
.addCourse(course)
.subscribe({
next: createdCourse => {
console.log(
'Course created:',
createdCourse
);
this.courses = [
...this.courses,
createdCourse
];
},
error: error => {
console.error(
'Create failed:',
error
);
}
});
}
Handling Update Response
updateCourse(course: Course) {
this.courseService
.updateCourse(
course.id,
course
)
.subscribe({
next: updatedCourse => {
this.courses =
this.courses.map(
item =>
item.id ===
updatedCourse.id
? updatedCourse
: item
);
},
error: error => {
console.error(
'Update failed:',
error
);
}
});
}
Handling Delete Response
deleteCourse(id: number) {
this.courseService
.deleteCourse(id)
.subscribe({
next: () => {
this.courses =
this.courses.filter(
course =>
course.id !== id
);
},
error: error => {
console.error(
'Delete failed:',
error
);
}
});
}
CIIT Training Institute Example
Consider an Angular admin dashboard used by CIIT Training Institute.
When the admin loads available courses, Angular sends a GET request. If the API succeeds, course data is displayed. If the request fails, an appropriate error message can be shown.
The same response-handling pattern can be applied to create, update and delete operations.
loadCourses() {
this.loading = true;
this.courseService
.getCourses()
.subscribe({
next: courses => {
this.courses = courses;
console.log(
'CIIT courses loaded'
);
},
error: error => {
this.errorMessage =
'Unable to load CIIT course data.';
console.error(error);
},
complete: () => {
this.loading = false;
}
});
}
Recommended Response Handling Flow
API Response Handling Best Practices
- Always handle possible API errors.
- Show an appropriate loading state for long-running requests.
- Use TypeScript types for predictable response structures.
- Display meaningful error messages to users.
- Keep API communication inside dedicated services.
- Avoid exposing technical error details directly to end users.
- Update the application state after a successful API operation.
Response Handling Quick Reference
| Callback | Purpose | Typical Use |
|---|---|---|
next
|
Handles successful emitted data. | Store response and update UI. |
error
|
Handles failed request. | Show error message. |
complete
|
Handles Observable completion. | Finish related processing. |
Summary
Angular API response handling is used to process the result of HTTP requests in a controlled way.
The next callback handles successful data, error handles failed requests and complete handles Observable completion.
Proper response handling makes Angular applications more reliable, user-friendly and easier to maintain.