Talking to the Server: HTTP in Angular
Master the fundamental skill of web communication in Angular by using the HttpClient service to fetch, create, update, and delete data.
/* Starting the connection... */
GET: Retrieving Data
The GET method is used to request and retrieve data from a server. It's a read-only operation. In Angular, you use http.get()
, which returns an Observable that you can subscribe to for the response.
POST: Creating Data
Use the POST method to send data to a server to create a new resource. The data is sent in the body of the request. The Angular method is http.post('/api/items', newItem)
.
PUT: Updating Data
The PUT method is used to update an existing resource on the server. You typically need to specify the resource's ID in the URL and send the updated data in the request body, like http.put('/api/items/123', updatedItem)
.
DELETE: Removing Data
To remove a resource from the server, use the DELETE method. This request usually only requires the ID of the resource to be deleted in the URL, for example: http.delete('/api/items/123')
.
Practice Zone
Interactive Test 1: Match the Method
Drag the correct HttpClient
method to its description.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build the Service
Complete the service by filling in the correct HTTP method names.
Rellena los huecos en cada casilla.
import { HttpClient } from '@angular/common/http'; export class DataService { constructor(private http: HttpClient) { } getData() { return this.http.('/api/data'); } createData(data: any) { return this.http.('/api/data', data); } updateData(id: string, data: any) { return this.http.('/api/data/' + id, data); } deleteData(id: string) { return this.http.('/api/data/' + id); } }
Practice Example: Code Your Own Service
Create a full Angular service named `ProductService` with a method `getProducts` that performs a GET request to `/api/products`.
Connecting the Pieces in Angular
Making HTTP requests in Angular involves three key parts working together: the Module, the Service, and the Component.
1. The Module: Enabling HTTP
Before you can do anything, you must import the HttpClientModule
in your root application module (usually app.module.ts
). This makes the HttpClient
service available for injection throughout your app.
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule // <-- Add this!
],
...
})
export class AppModule { }
2. The Service: Managing Requests
Services are the perfect place to centralize your HTTP logic. You create a service, inject HttpClient
into its constructor, and define methods for each API endpoint you need to call.
// data.service.ts
@Injectable({ providedIn: 'root' })
export class DataService {
constructor(private http: HttpClient) { }
getItems() {
return this.http.get('/api/items');
}
}
3. The Component: Using the Data
Finally, your component injects the service. It calls the service's methods and—crucially—subscribes to the returned Observable to trigger the request and receive the data when it arrives.
// my.component.ts
export class MyComponent implements OnInit {
items: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getItems().subscribe(data => {
this.items = data;
});
}
}
Practical Takeaway: Remember the flow: Module provides the tool (HttpClient), Service uses the tool to define requests, and Component calls the service and subscribes to get the results.
Angular HTTP Glossary
- HttpClient
- An Angular service for making HTTP requests. You inject it into your services to communicate with a server.
- HttpClientModule
- The module that provides the
HttpClient
service. It must be imported into your application module. - Observable
- A stream of data that can be delivered over time. All
HttpClient
methods return Observables, which don't do anything until subscribed to. - subscribe()
- The method used to execute an Observable. You call
.subscribe()
on the result of an HTTP call to send the request and listen for the response. - API Endpoint
- The URL on a server that your application sends requests to (e.g., `/api/users` or `https://api.example.com/products`).
- Service
- A class in Angular designed to share data and logic across components. It is the recommended place to manage all HTTP communications.