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 |
Angular applications commonly communicate with backend APIs through HttpClient, using HTTP methods such as GET, POST, PUT, PATCH, and DELETE. The article's task-service example shows how these operations can be encapsulated in a reusable Angular service rather than placed directly inside a component.
ReplyDeleteThe step-by-step setup makes the API workflow practical, from configuring HTTP support to defining a typed Task interface and creating service methods. Developers working through Angular Online Course can use this structure to keep API communication organized and reusable across components.
The use of Observable and other typed Observable responses also demonstrates how Angular services can work with RxJS when handling asynchronous HTTP operations. This makes the example relevant for developers learning TypeScript Online Course, particularly because the Task interface provides clear typing for data exchanged with the API.
ReplyDeleteThe final component example shows the service being injected and used during ngOnInit() to retrieve tasks and assign the returned data to the component state. This service-based API pattern is directly applicable when building Angular Projects that need to connect an Angular frontend with backend data services.
ReplyDelete