One of the most common real-world tasks in Angular is 👉 Communicating with Data Services over HTTP
(a.k.a. making API calls). Let’s break it down step by step.
🌐 Goal: Talk to a backend (API) from
Angular
Angular uses the HttpClient
service from the @angular/common/http package to:
- Fetch
data (GET)
- Send
data (POST)
- Update
data (PUT/PATCH)
- Delete
data (DELETE)
🔧 Step-by-Step: Setup & Usage
✅ 1. Import HttpClientModule
In app.module.ts:
import {
HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
// other modules
]
})
export class AppModule {}
✅ 2. Create a Data Service
Generate a service:
ng generate service
task
Inside
task.service.ts:
import { Injectable }
from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Task
{
id: number;
title: string;
completed: boolean;
}
@Injectable({
providedIn: 'root' })
export class TaskService {
private apiUrl = 'https://api.example.com/tasks'; //
your backend endpoint
constructor(private
http: HttpClient) {}
// GET all tasks
getTasks(): Observable<Task[]> {
return
this.http.get<Task[]>(this.apiUrl);
}
// POST a new task
addTask(task: Partial<Task>):
Observable<Task> {
return
this.http.post<Task>(this.apiUrl, task);
}
// DELETE a task
deleteTask(id: number):
Observable<void> {
return
this.http.delete<void>(`${this.apiUrl}/${id}`);
}
// PUT to update task
updateTask(task: Task):
Observable<Task> {
return
this.http.put<Task>(`${this.apiUrl}/${task.id}`, task);
}
}
✅ 3. Use the Service in a Component
In
task-list.component.ts:
import { Component,
OnInit } from '@angular/core';
import { TaskService, Task } from '../task.service';
@Component({
selector: 'app-task-list',
templateUrl:
'./task-list.component.html'
})
export class TaskListComponent implements OnInit {
tasks: Task[] = [];
constructor(private
taskService: TaskService) {}
ngOnInit() {
this.taskService.getTasks().subscribe(data => {
this.tasks = data;
});
}
deleteTask(id:
number) {
this.taskService.deleteTask(id).subscribe(() => {
this.tasks = this.tasks.filter(t
=> t.id !== id);
});
}
}
✅ 4. Template (task-list.component.html)
<ul>
<li *ngFor="let task of
tasks">
{{ task.title }}
<button
(click)="deleteTask(task.id)">Delete</button>
</li>
</ul>
⚠️ Error Handling (Optional but Recommended)
Use catchError() with
RxJS:
import { catchError }
from 'rxjs/operators';
import { throwError } from 'rxjs';
getTasks():
Observable<Task[]> {
return
this.http.get<Task[]>(this.apiUrl).pipe(
catchError(error => {
console.error('Error fetching
tasks', error);
return throwError(() => new
Error('Failed to fetch tasks'));
})
);
}
🧠 Summary
Step |
What
You Do |
1 |
Import
HttpClientModule |
2 |
Inject
HttpClient in a service |
3 |
Use
get/post/put/delete to talk to API |
4 |
Subscribe
in components to get data |
No comments:
Post a Comment