1. What is HttpClient in Angular?
In Angular, API communication is done using:
HttpClient
It is provided by:
@angular/common/http
HttpClient:
Sends HTTP requests to backend
Returns Observable
Supports interceptors
Supports headers, params, tokens
Setup HttpClient in Angular 21
Step 1: Import HttpClientModule (Standalone Angular 21)
Angular 21 uses standalone by default.
👉 main.ts
import { provideHttpClient } from '@angular/common/http';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient()
]
});import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, FormsModule],
templateUrl: './app.component.html'
})
export class AppComponent {
apiUrl = 'https://jsonplaceholder.typicode.com/posts';
responseData: any;
// User Input Model
postData = {
id: '',
title: '',
body: '',
userId: ''
};
// Dummy Token (Normally comes from login API)
token = '1234567890abcdef';
constructor(private http: HttpClient) {}
// Common Headers with Token
getHeaders() {
return new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.token}`
});
}
// GET
getPosts() {
this.http.get(this.apiUrl, { headers: this.getHeaders() })
.subscribe(res => this.responseData = res);
}
// POST
createPost() {
this.http.post(this.apiUrl, this.postData, { headers: this.getHeaders() })
.subscribe(res => this.responseData = res);
}
// PUT (Full Update)
updatePost() {
this.http.put(`${this.apiUrl}/${this.postData.id}`, this.postData,{ headers: this.getHeaders() })
.subscribe(res => this.responseData = res);
}
// PATCH (Partial Update)
patchPost() {
const partialData = {
title: this.postData.title
};
this.http.patch(`${this.apiUrl}/${this.postData.id}`, partialData,{ headers: this.getHeaders() })
.subscribe(res => this.responseData = res);
}
// DELETE
deletePost() {
this.http.delete(`${this.apiUrl}/${this.postData.id}`,{ headers: this.getHeaders() })
.subscribe(res => this.responseData = res);
}
}Step 3: HTML Template
👉 app.component.html
<h2>Angular All API Example</h2>
<div style="margin-bottom:20px;">
<label>ID:</label>
<input [(ngModel)]="postData.id" placeholder="Enter ID for update/delete">
<label>Title:</label>
<input [(ngModel)]="postData.title" placeholder="Enter Title">
<label>Body:</label>
<input [(ngModel)]="postData.body" placeholder="Enter Body">
<label>UserId:</label>
<input [(ngModel)]="postData.userId" placeholder="Enter UserId">
</div>
<div style="margin-bottom:20px;">
<button (click)="getPosts()">GET</button>
<button (click)="createPost()">POST</button>
<button (click)="updatePost()">PUT</button>
<button (click)="patchPost()">PATCH</button>
<button (click)="deletePost()">DELETE</button>
</div>
<h3>Response:</h3>
<pre>{{ responseData | json }}</pre>CREATE REAL-TIME LOGIN & DASHBOARD USING DUMMY API✅ Dummy Login Form
✅ Dummy Login API (fake API call using Observable)
✅ Store fake token
✅ Navigate to Dashboard
We will create:
Login Component
Dashboard Component
Auth Service
Routing
Step 1: Setup Routing (main.ts)
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideHttpClient()
]
});
Step 2: Create Routes
👉 app.routes.ts
import { Routes } from '@angular/router';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';
export const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent }
];
Step 3: Create Auth Service (Dummy API)
👉 auth.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { private loginUrl = 'https://fakestoreapi.com/auth/login'; constructor(private http: HttpClient) {} login(username: string, password: string): Observable<any> { const body = { username: username, password: password }; return this.http.post(this.loginUrl, body); } }
Step 4: Login Component
👉 login.component.ts
import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { Router } from '@angular/router'; import { AuthService } from './auth.service'; @Component({ selector: 'app-login', standalone: true, imports: [CommonModule, FormsModule], templateUrl: './login.component.html' }) export class LoginComponent { username = ''; password = ''; errorMessage = ''; loading = false; constructor( private authService: AuthService, private router: Router ) {} login() { this.loading = true; this.errorMessage = ''; this.authService.login(this.username, this.password) .subscribe({ next: (res) => { this.loading = false; if (res.token) { localStorage.setItem('token', res.token); this.router.navigate(['/dashboard']); } }, error: (err) => { this.loading = false; this.errorMessage = 'Invalid Username or Password'; } }); } }
login.component.html
<h2>Login (FakeStore API)</h2> <div style="width:300px"> <label>Username:</label> <input [(ngModel)]="username" placeholder="Enter username"> <br><br> <label>Password:</label> <input type="password" [(ngModel)]="password" placeholder="Enter password"> <br><br> <button (click)="login()" [disabled]="loading"> {{ loading ? 'Logging in...' : 'Login' }} </button> <p style="color:red">{{ errorMessage }}</p> <p><b>Use Demo Credentials:</b></p> <p>Username: mor_2314</p> <p>Password: 83r5^_</p> </div>
Step 6: Dashboard Component
dashboard.component.ts
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Router } from '@angular/router'; @Component({ selector: 'app-dashboard', standalone: true, imports: [CommonModule], templateUrl: './dashboard.component.html' }) export class DashboardComponent { token = localStorage.getItem('token'); constructor(private router: Router) {} logout() { localStorage.removeItem('token'); this.router.navigate(['/']); } }dashboard.component.html
<h2>Dashboard</h2> <p>Login Successful 🎉</p> <p><b>Stored Token:</b></p> <pre>{{ token }}</pre> <button (click)="logout()">Logout</button>TypeScript Code:import { Component, ChangeDetectorRef } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-apipractice', imports: [CommonModule,FormsModule], templateUrl: './apipractice.html', styleUrl: './apipractice.css', }) export class Apipractice { apiUrl = 'http://localhost:3001/posts'; token=''; responseData: any[]=[]; id:number=0 name:string='' email:string='' address:string='' result:string='' constructor(private http: HttpClient,private cd: ChangeDetectorRef) { } // Common Headers with Token getHeaders() { return new HttpHeaders({ 'Content-Type': 'application/json' // 'Authorization': `Bearer ${this.token}` }); } // GET createProduct() { this.http.post(this.apiUrl, { "id": this.id, "name": this.name, "email": this.email, "address": this.address }, { headers: this.getHeaders() }) .subscribe(res => {this.result = 'record addedd successfully'; this.getUserDetails(); }); } findProduct(id: number) { this.http.get<any>(`${this.apiUrl}/${id}`).subscribe({ next: (res) => { this.id = res.id; this.name = res.name; this.email = res.email; this.address = res.address; this.cd.detectChanges(); // force UI update }, error: (err) => console.error(err) }); } updateProduct() { this.http.put(`${this.apiUrl}/${this.id}`,{ name: this.name, email: this.email, address: this.address },{headers: this.getHeaders()}).subscribe(res => { this.result = 'record modified successfully'; this.getUserDetails(); }); } deleteProduct(id:number) { const confirmDelete = confirm(`Are you sure you want to delete record with ID ${id}?`); if(confirmDelete) { this.http.delete(`${this.apiUrl}/${id}`).subscribe(rres => {this.result = 'record deleted successfully'; this.getUserDetails(); this.cd.detectChanges(); }); } } getUserDetails() { this.http.get<any[]>(this.apiUrl) .subscribe({ next: (res) => { this.responseData = res; this.cd.detectChanges(); }, error: (err) => console.error(err) }); } }.Html File:<p>apipractice works!</p> <h3>Response:</h3> <input type="text" placeholder="Enter ID" [(ngModel)]="id" name="id" /> <input type="text" placeholder="Enter name" [(ngModel)]="name" name="name" /> <input type="text" placeholder="Enter email" [(ngModel)]="email" name="email" /> <input type="text" placeholder="Enter address" [(ngModel)]="address" name="address" /><br/><br/> <button (click)="createProduct()">Add Product</button> <br><br> <button (click)="updateProduct()">Update Product</button><br><br> <button (click)="getUserDetails()">View All Records</button><br><br> <table> <tr><th>ID</th><th>Name</th><th>Email</th><th>Address</th></tr> <tr *ngFor="let item of responseData"> <td>{{ item.id }}</td> <td>{{ item.name }}</td><td>{{item.email}}</td><td>{{ item.address }}</td> <td><button (click)="findProduct(item.id)">Find Product</button></td><td><button (click)="deleteProduct(item.id)">delete Product</button></td> </tr> </table>

0 Comments
POST Answer of Questions and ASK to Doubt