Day 02 Core Concepts

Services and Dependency Injection

Angular services hold shared logic and data. Dependency Injection delivers them to any component that asks. This is how Angular apps share state and commun

~1 hour Hands-on Precision AI Academy

Today's Objective

Angular services hold shared logic and data. Dependency Injection delivers them to any component that asks. This is how Angular apps share state and commun

01

Why Services Exist

Components should handle display. Services handle logic, data, and communication. A component that fetches data directly is harder to test and harder to reuse. Extract that work into a service.

Terminal
Terminal
ng generate service task
# creates: task.service.ts
task.service.ts
task.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'  // available app-wide, no need to register
})
export class TaskService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/todos';

  constructor(private http: HttpClient) {}

  getTasks(): Observable {
    return this.http.get(this.apiUrl);
  }

  deleteTask(id: number): Observable {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}
💡
Register HttpClientModule in app.module.ts imports, or Angular can't inject HttpClient into your service.
02

Injecting a Service into a Component

task-list.component.ts
task-list.component.ts
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: any[] = [];
  loading = true;
  error = '';

  // Angular injects TaskService automatically via DI
  constructor(private taskService: TaskService) {}

  ngOnInit(): void {
    this.taskService.getTasks().subscribe({
      next: (data) => { this.tasks = data.slice(0, 20); this.loading = false; },
      error: (err) => { this.error = 'Failed to load'; this.loading = false; }
    });
  }
}
task-list.component.html
task-list.component.html
Loading...

{{ error }}

  • {{ task.title }} ✓
03

The async Pipe

Instead of subscribing manually in ngOnInit, you can pass an Observable directly to the template and use the async pipe. It subscribes, unwraps, and unsubscribes automatically.

Component (simplified)
Component (simplified)
tasks$ = this.taskService.getTasks();  // Observable, not subscribed yet
Template
Template
  • {{ task.title }}
  • Supporting References & Reading

    Go deeper with these external resources.

    Docs
    Services and Dependency Injection Official documentation for angular.
    GitHub
    Services and Dependency Injection Open source examples and projects for Services and Dependency Injection
    MDN
    MDN Web Docs Comprehensive web technology reference

    Day 2 Checkpoint

    Before moving on, confirm understanding of these key concepts:

    Continue To Day 3
    Day 3 of the Angular in 5 Days course