In Angular, you can perform HTTP requests using the ‘HttpClient‘ module. Before you start, you need to make sure that you import the ‘HttpClientModule‘ in your ‘app.module.ts‘ file:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
// Other imports ...
HttpClientModule
],
// Declarations, Providers, ...
})
export class AppModule { }
After importing the ‘HttpClientModule‘, you can now inject the ‘HttpClient‘ in your service or components. Here’s an example of a service that performs HTTP requests to a REST API:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private API_URL = 'https://api.example.com';
constructor(private http: HttpClient) { }
// Get list of items
getItems(): Observable<any> {
return this.http.get(`${this.API_URL}/items`);
}
// Get item by id
getItemById(id: number): Observable<any> {
return this.http.get(`${this.API_URL}/items/${id}`);
}
// Create new item
createItem(data: any): Observable<any> {
return this.http.post(`${this.API_URL}/items`, data);
}
// Update item by id
updateItem(id: number, data: any): Observable<any> {
return this.http.put(`${this.API_URL}/items/${id}`, data);
}
// Delete item by id
deleteItem(id: number): Observable<any> {
return this.http.delete(`${this.API_URL}/items/${id}`);
}
}
In this example, ‘ApiService‘ performs HTTP requests to a REST API for different CRUD operations: get, create, update, and delete items. The ‘HttpClient‘ is injected in the constructor to make it available within the service.
Here’s a brief explanation of each method and how it uses ‘HttpClient‘:
- ‘getItems()‘: Gets the list of items from the ‘/items‘ endpoint using ‘this.http.get‘.
- ‘getItemById(id: number)‘: Gets a specific item by its ‘id‘ from the ‘/items/:id‘ endpoint using ‘this.http.get‘.
- ‘createItem(data: any)‘: Creates a new item by sending a POST request with the ‘data‘ payload to the ‘/items‘ endpoint using ‘this.http.post‘.
- ‘updateItem(id: number, data: any)‘: Updates an existing item by sending a PUT request with the ‘data‘ payload to the ‘/items/:id‘ endpoint using ‘this.http.put‘.
- ‘deleteItem(id: number)‘: Deletes an item by its ‘id‘ from the ‘/items/:id‘ endpoint using ‘this.http.delete‘.
By using this service, you can send HTTP requests to a REST API and handle the CRUD operations in your Angular application.