Services
HttpClient
Master Angular HttpClient, covering GET/POST/PUT/DELETE requests, typed responses, error handling, query parameters, and headers configuration.
1. Learning Objectives
In this lesson, you will master Angular's HttpClient. By the end of this topic, you will be able to:
- Configure
provideHttpClient()for standalone applications. - Make typed HTTP requests using GET, POST, PUT, and DELETE methods.
- Handle HTTP errors using
catchErrorand theHttpErrorResponsetype. - Set custom headers and query parameters on requests.
- Understand why HttpClient returns cold observables that require subscription.
2. Overview
Angular's HttpClient is a service for making HTTP requests to backend APIs. It is built on top of the browser's XMLHttpRequest API and returns RxJS observables, making it easy to compose, transform, and cancel requests. Unlike the native fetch API, HttpClient provides typed responses, automatic JSON parsing, request/response interception, and built-in testing utilities.
3. Why This Topic Matters
HttpClient is the standard way to communicate with backend APIs in Angular:
- Cold Observable Trap: HttpClient methods return cold observables. The HTTP request is only sent when something subscribes. If you call
http.get()without subscribing, the request is never made. This is a common source of bugs where developers expect the request to fire immediately. - Unhandled Errors: If an HTTP request fails and there is no
catchErrorhandler in the observable pipeline, the error propagates to the component's subscription, potentially crashing the component without user feedback.
4. Real-World Analogy
Think of HttpClient like **a postal mail service**:
- GET (Requesting a catalog): You mail a request to a company asking for their product catalog. The company sends back a package (response body) containing the catalog.
- POST (Sending an order form): You mail a filled-out order form to the company. The company processes it and sends back an order confirmation number.
- Cold Observable (Stamped but unsent letter): Writing the letter and stamping it (calling
http.get()) does not send it. You must take it to the mailbox (subscribe) for the postal service to actually deliver it. - Error Handling (Lost package): If the postal service loses your package, you need a tracking system (catchError) to detect the failure and take corrective action, like resending the letter.
5. Core Concepts
Angular HttpClient provides the following core features:
| HTTP Method | Purpose | Request Body |
|---|---|---|
| GET | Retrieve data from the server. | No body (uses query parameters). |
| POST | Send data to create a new resource. | JSON body (automatically serialized). |
| PUT | Replace an entire resource. | JSON body with full resource data. |
| DELETE | Remove a resource. | Typically no body. |
6. Syntax & API Reference
First, register provideHttpClient() at application bootstrap:
Below is a service that wraps HttpClient for typed CRUD operations:
7. Visual Diagram
This diagram displays the HttpClient request-response lifecycle:
8. Live Example — Full Working Code
Below is a component that uses the ProductService to fetch and display products:
9. Interactive Playground
Try It Yourself Challenges:
- Add a search filter that passes a
categoryquery parameter to the GET request. - Remove the
.subscribe()call from a request and verify the HTTP request is never sent (check Network tab).
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Not subscribing to HTTP observables | Calling http.get() without subscribing. Cold observables only execute when subscribed. The request is never sent. |
this.http.get('/api/data'); |
this.http.get('/api/data').subscribe(...); |
| Missing provideHttpClient registration | Injecting HttpClient without registering provideHttpClient() at bootstrap, causing a "NullInjectorError: No provider for HttpClient". |
providers: [provideRouter(routes)] |
providers: [provideRouter(routes), provideHttpClient()] |
11. Best Practices
- Always handle errors: Use
catchErrorin the service or theerrorcallback in the subscription to display meaningful error messages to users. - Use typed responses: Always pass a generic type parameter to HTTP methods (e.g.,
http.get<Product[]>(url)) for compile-time type safety. - Wrap HttpClient in services: Never inject
HttpClientdirectly into components. Create dedicated service classes that encapsulate API endpoints and error handling logic. - Use HttpParams for query strings: Build query parameters using the
HttpParamsclass rather than manually concatenating URL strings, which is error-prone and harder to maintain.
12. Browser Compatibility/Requirements
HttpClient is built on top of the browser's XMLHttpRequest API and works consistently across all modern browsers. For server-side rendering (SSR), Angular provides a server-compatible HTTP backend automatically.
13. Interview Questions
Q1: Why does Angular's HttpClient return observables instead of promises?
Answer: Observables provide several advantages over promises: they are lazy (the request is only sent when subscribed), cancellable (unsubscribing cancels the request), and composable (you can chain operators like map, retry, debounceTime). Promises are eager and cannot be cancelled once started.
Q2: What happens if you call http.get() but never subscribe to the returned observable?
Answer: The HTTP request is never sent. HttpClient returns cold observables, which means the underlying HTTP call only executes when a subscriber is attached. Without a subscription, no network request is made.
14. Debugging Exercise
The product list never loads data even though the API is running. Identify the bug:
Diagnosis: The loadProducts() method calls http.get() but does not return the observable, and the component does not subscribe to it. Since HttpClient returns cold observables, the HTTP request is never sent without a subscription.
Fix:
15. Practice Exercises
Exercise 1: Build a complete CRUD interface
Create a TaskService with methods for all four CRUD operations (GET all, GET by ID, POST, PUT, DELETE). Build a component that displays a task list, allows adding new tasks via a form, editing existing tasks, and deleting tasks with confirmation.
16. Scenario-Based Challenge
The Retry and Fallback Challenge:
An application fetches weather data from a primary API. If the primary API fails, it should retry twice, then fall back to a secondary API endpoint. Implement this using RxJS operators (retry and catchError) within an HttpClient service method.
17. Quick Quiz
Q1: What type of observable does HttpClient return?
A) Hot observable (executes immediately)
B) Cold observable (executes on subscription)
C) Warm observable (executes after a delay)
Answer: B — HttpClient returns cold observables that only execute the HTTP request when subscribed to.
18. Summary & Key Takeaways
- HttpClient returns cold observables — always subscribe to trigger the actual HTTP request.
- Use typed generic parameters on all HTTP methods for compile-time type safety.
- Always handle errors with
catchErrorto prevent silent failures and provide user feedback. - Wrap all HttpClient usage inside dedicated service classes — never inject HttpClient directly into components.
19. Cheat Sheet
| Method | Purpose |
|---|---|
http.get<T>(url, options) |
Retrieve data from the server. |
http.post<T>(url, body, options) |
Send data to create a new resource. |
HttpParams |
Build URL query parameters immutably. |
HttpHeaders |
Set custom request headers immutably. |