Skip to main content
Angular Basics
CHAPTER 09 Beginner

Angular Services and Dependency Injection

Updated: May 18, 2026
5 min read

# CHAPTER 9

Angular Services and Dependency Injection

1. Chapter Introduction

Components should only handle the UI — displaying data and responding to user actions. Fetching data from APIs, managing application state, or calculating business logic inside a component creates "fat components" that are impossible to test and reuse. Services are Angular's solution. A Service is a class that handles data logic. Dependency Injection (DI) is Angular's system for automatically providing a Service to any component that needs it.

2. Learning Objectives

  • Understand why Services are needed.
  • Create a service using the Angular CLI.
  • Understand the @Injectable decorator.
  • Inject a service into a component.
  • Share state between multiple components via a singleton service.

3. Creating a Service

bash
1
ng g service task

This generates task.service.ts:

typescript
123456789101112131415161718192021
import { Injectable } from '@angular/core';

// 'providedIn: root' makes this a Singleton — one instance for the entire app
@Injectable({
  providedIn: 'root'
})
export class TaskService {
  private tasks: string[] = ['Buy groceries', 'Learn Angular', 'Exercise'];

  getTasks(): string[] {
    return this.tasks;
  }

  addTask(task: string): void {
    this.tasks.push(task);
  }

  deleteTask(index: number): void {
    this.tasks.splice(index, 1);
  }
}

4. Dependency Injection: Using the Service

To use a service, you inject it through the component's constructor. Angular's DI system automatically creates the instance!
typescript
12345678910111213141516171819202122232425
import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-task-list',
  templateUrl: './task-list.component.html'
})
export class TaskListComponent implements OnInit {
  tasks: string[] = [];
  newTask: string = '';

  // Angular sees TaskService in the constructor and provides an instance automatically
  constructor(private taskService: TaskService) {}

  ngOnInit(): void {
    this.tasks = this.taskService.getTasks();
  }

  addTask(): void {
    if (this.newTask.trim()) {
      this.taskService.addTask(this.newTask);
      this.newTask = '';
    }
  }
}
html
123456
<input [(ngModel)]="newTask" placeholder="New Task" />
<button (click)="addTask()">Add</button>

<ul>
  <li *ngFor="let task of tasks">{{ task }}</li>
</ul>

5. Singleton: Shared State Between Components

Because providedIn: 'root' creates a single shared instance, two different components injecting the same service share the same data!
text
1234567
TaskService (Singleton)
   |
   +---- TaskListComponent (reads tasks)
   |
   +---- TaskCountComponent (reads tasks.length)
   |
   +---- TaskFormComponent (adds tasks)

All three components look at the same TaskService instance. When TaskFormComponent adds a task, TaskListComponent and TaskCountComponent automatically reflect the update.

6. Mini Project: Task Manager Service

Complete working task manager using a service to coordinate two components.
task-form.component.ts
123456789
export class TaskFormComponent {
  newTask = &#039;&#039;;
  constructor(private taskService: TaskService) {}
  
  onSubmit() {
    this.taskService.addTask(this.newTask);
    this.newTask = &#039;&#039;;
  }
}
task-count.component.ts
1234567
export class TaskCountComponent {
  constructor(public taskService: TaskService) {}
  
  get count(): number {
    return this.taskService.getTasks().length;
  }
}

7. Common Mistakes

  • Creating service instances with new: Never write let service = new TaskService() in a component. This bypasses the DI system and creates a separate, unshared instance that defeats the Singleton pattern.
  • Business logic in components: If you write API calls directly in ngOnInit of a component without a service, that component becomes impossible to test and reuse.

8. Best Practices

  • One service per responsibility: Create AuthService for auth, ProductService for products. Don't put all logic in one giant service.
  • Make services pure: Services should not depend on Angular's UI or DOM. This keeps them testable with simple unit tests.

9. MCQs with Answers

Question 1

What is the primary purpose of an Angular Service?

Question 2

What decorator marks a class as an Angular Service?

Question 3

What does providedIn: 'root' mean?

Question 4

How do you inject a service into a component?

Question 5

Why should you never manually instantiate a service using new MyService()?

Q6. If two components inject the same service (with providedIn: 'root'), do they share the same data? a) No, each gets its own copy b) Yes, they share the same Singleton instance Answer: b) Yes, they share the same Singleton.
Question 7

What Angular CLI command generates a service named auth?

Question 8

Which lifecycle hook is best for calling a service to load initial data?

Question 9

What is Dependency Injection?

Q10. Should components directly make HTTP API calls? a) Yes, for simplicity b) No, API calls should be delegated to a Service to keep components focused on UI logic Answer: b) No, delegate to a Service.

10. Interview Questions

  • Q: What is the Singleton Pattern in Angular Services? Why is it useful?
  • Q: Explain Dependency Injection in Angular. How does the framework know which service to provide to which component?

11. Summary

Services and Dependency Injection are the backbone of clean Angular architecture. By centralizing all data logic in dedicated service classes and letting Angular's DI system wire them together, we achieve the holy grail of software design: loosely coupled, highly testable, and reusable code.

12. Next Chapter Recommendation

Our app currently has only one view. In Chapter 10: Angular Routing and Navigation, we will learn how to build multi-page SPAs, navigate between views, pass parameters in URLs, and implement lazy loading for performance.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·