Skip to main content

Overview

The HttpClient service provides a powerful and flexible API for making HTTP requests in Angular applications. It returns RxJS Observables, enabling reactive programming patterns and composable data streams.

Setup

Standalone applications

Provide HttpClient in your application configuration:
app.config.ts

Module-based applications

Import HttpClientModule in your application module:
app.module.ts
For server-side rendering applications, use withFetch() for better performance:

Injecting HttpClient

Inject HttpClient into your services or components:
user.service.ts

HTTP Methods

GET requests

Retrieve data from the server:

POST requests

Send data to create new resources:

PUT requests

Update existing resources:

PATCH requests

Partially update resources:

DELETE requests

Remove resources:

Request Options

Query parameters

Add URL query parameters using the params option:

Headers

Customize request headers:

Response types

Specify the expected response type:

Observing responses

Control what information is returned:

Working with Observables

Basic subscription

RxJS operators

Transform HTTP responses using RxJS operators:

Combining multiple requests

Sequential requests

Type safety

Provide type information for responses:

Advanced options

Request credentials

Request timeout

Transfer cache (SSR)

Best practices

Use services for HTTP callsEncapsulate HTTP logic in dedicated services rather than making calls directly from components.
Provide type informationAlways specify generic types for type-safe responses: http.get<User[]>('/api/users')
Handle errors appropriatelyUse error handlers or the catchError operator to gracefully handle failed requests.
HTTP requests are not executed until you subscribe to the Observable. Always remember to subscribe, or use operators like toPromise() or the async pipe in templates.
Unsubscribe when neededFor long-lived subscriptions in components, unsubscribe in ngOnDestroy or use the async pipe which automatically unsubscribes.

Next steps

Interceptors

Transform requests and responses globally with HTTP interceptors.

Error handling

Handle HTTP errors and implement retry logic.