When
you have complex tasks (like fetching data, doing calculations, handling
app-wide logic), Services are the go-to solution.
đź’ˇ What is a Service in Angular?
A Service is a
TypeScript class with a specific purpose — it contains reusable logic
that isn’t directly tied to the UI.
âś…
Think of services as your app’s “helpers” or “managers.”
They handle:
- HTTP
requests
- Data
transformation
- Business
logic
- State
management
- Communication
between components
đź§ Why Use Services for Complex Tasks?
- Separation
of concerns
– Keep components focused on displaying the UI.
- Reusability – One service,
multiple components can use it.
- Testability – Easier to
unit test logic inside services.
- Cleaner
components
– Logic stays in the service, not bloating the component.
🛠️ How to Create & Use a Service
Let’s say we’re
building a Task Manager app, and we need a service to handle tasks.
1. Create a Service
ng generate service
task
2. task.service.ts
import { Injectable }
from '@angular/core';
@Injectable({
providedIn: 'root' // Makes it globally available
})
export class TaskService {
private tasks: string[] = [];
addTask(task: string)
{
this.tasks.push(task);
}
getTasks(): string[]
{
return [...this.tasks]; // Return a
copy
}
deleteTask(index:
number) {
this.tasks.splice(index, 1);
}
}
3. Use it in a Component
task-list.component.ts
import { Component }
from '@angular/core';
import { TaskService } from '../task.service';
@Component({
selector: 'app-task-list',
templateUrl:
'./task-list.component.html',
})
export class TaskListComponent {
tasks: string[] = [];
constructor(private
taskService: TaskService) {}
ngOnInit() {
this.tasks =
this.taskService.getTasks();
}
deleteTask(index:
number) {
this.taskService.deleteTask(index);
this.tasks =
this.taskService.getTasks(); // Refresh the list
}
}
task-list.component.html
<ul>
<li *ngFor="let task of tasks;
let i = index">
{{ task }}
<button
(click)="deleteTask(i)">Delete</button>
</li>
</ul>
⚙️ Services + HTTP (Real World)
Want to manage tasks
via an API? Inject Angular’s HttpClient into the service and replace the array
logic with HTTP calls.
import { HttpClient }
from '@angular/common/http';
constructor(private
http: HttpClient) {}
getTasksFromAPI() {
return
this.http.get<Task[]>('https://api.example.com/tasks');
}
đź§ Summary
Concept |
Purpose |
Service |
Manages
logic, data, and reusability |
Component |
Displays
UI and connects to services |
Why? |
Keeps
code clean, testable, and scalable |
No comments:
Post a Comment