"jjj"
Angular Http
Angular HttpClient – Fetching Data from APIs
With Angular's HttpClient, connecting your app to external APIs becomes seamless and efficient—just plug, play, and fetch!
Setup
To start making HTTP requests in Angular, bring HttpClientModule into your module's imports—it’s your gateway to server communication.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [ HttpClientModule ]
})
export class AppModule {}
Making Requests
Inject HttpClient in your component and call .get() to fetch data.
Example: Show a welcome message from the server
<!-- app.component.html -->
<p>Today's welcome message is:</p>
<h1>{{ welcomeMessage }}</h1>
Other HTTP Methods
Angular's HttpClient supports:
this.http.get(url); this.http.post(url, body); this.http.put(url, body); this.http.delete(url); this.http.patch(url, body);
Handling Errors
You can catch errors using catchError.
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
this.http.get('assets/data.json')
.pipe(
catchError(error => {
this.error = 'Failed to load data';
return throwError(() => error);
})
)
.subscribe(data => this.data = data);
Working with JSON
If your API returns JSON (most do!), HttpClient automatically parses it for you.
Example: Load and display a list of users
// user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
<component>({
selector: 'app-user-list',
templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
users: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('https://jsonplaceholder.typicode.com/users')
.subscribe(data => this.users = data);
}
}
Response Object
- Each response includes:
- status → HTTP status code
- body → the actual data
- headers → response headers
- url → request URL
Summary
| Task | Code Sample |
|---|---|
| Import module | HttpClientModule |
| Make GET request | http.get(url) |
| Error handling | catchError(() => ...) |
| Display data | *ngFor="let item of items" |
| Text response | { responseType: 'text' } |
Prefer Learning by Watching?
Watch these YouTube tutorials to understand ANGULAR Tutorial visually:
What You'll Learn:
- 📌 Angular HTTP Client Quick Start Tutorial
- 📌 HTTP in Angular - Learning Angular (Part 8)