Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

API Calling with HttpClient in Angular

 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>


Post a Comment

0 Comments