Friday, 18 April 2025

Angular 19 | Chapter 5 | Handle Complex Tasks with Services In Angular

 

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

 

3 comments:

  1. Angular services provide a clean way to move reusable logic out of components and keep UI code focused on presentation. The article highlights common responsibilities such as HTTP requests, data transformation, business logic, state management, and communication between components.

    The separation-of-concerns approach is particularly useful because a single service can be reused by multiple components while also making its logic easier to test. Developers working with Angular Online Training can apply this pattern to keep larger applications more maintainable.

    ReplyDelete
  2. The TaskService example demonstrates dependency injection with providedIn: 'root', along with methods for adding, retrieving, and deleting tasks. This also gives developers studying TypeScript Online Training a practical example of organizing reusable application logic inside a typed class.

    ReplyDelete
  3. Using a dedicated service becomes increasingly valuable as an application grows and multiple components need to share the same operations or data. The task-manager example provides a simple foundation that can be extended in Angular Projects involving shared business logic and application-level services.

    ReplyDelete