In Angular, we can use the built-in HttpClientModule to make HTTP requests to a server.
HttpClientModule makes HTTP requests using the browser's XMLHttpRequest interface and provides features such as request and response interception, error handling, and observables-based APIs.
Let's explore how we can use the `HttpClientModule` in Angular, along with an example:
First, we need to import "HttpClientModule" in our Angular module (typically "AppModule") to make the HTTP client available throughout our application.
import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ // your components ], imports: [ BrowserModule, HttpClientModule // Import HttpClientModule here ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Next, we can inject "HttpClient" in a service or component where we can make HTTP requests.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class YourDataService { constructor(private http: HttpClient) { } // Inject HttpClient // Call this function from component when page loads getUserDetails(): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/todos/1'); } }
import { Component, OnInit } from '@angular/core'; import { YourDataService } from './your-data.service'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { userDetails: any; // Inject service in component constructor(private yourDataService: YourDataService) { } ngOnInit(): void { // calling service data this.yourDataService.getUserDetails().subscribe( (response) => { this.userDetails = response; }, (error) => { console.error('Error while fetching service data:', error); }); } }
We are consuming the `YourDataService` service in a component and subscribing to the Observable returned by the `getUserDetails()` method to fetch data.
we're using "subscribe" to handle the response from the HTTP request.
we should handle errors as well. we can use "operators" like "catchError" from "RxJS" for error handling.
<div *ngIf="userDetails"> <h2>User Info:</h2> <pre>{{ userDetails | json }}</pre> </div>
displaying the fetched user details data in the component template.
The HttpClient module provides a simple and powerful API for making HTTP requests.
Make sure to handle HTTP error responses appropriately, especially in production code.
Don't forget to unsubscribe from the Observable when the component is destroyed to prevent memory leaks, especially for long-lived Observables.