4. Angular Services & Dependency Injection

Encapsulate logic, share state, and wire everything together with DI

Components should be thin. They own a template and handle user interaction — that's it. The real logic — HTTP calls, data transformation, business rules, shared state — belongs in services. Angular's dependency injection (DI) system makes services available to any component, directive, or other service that needs them, without manual wiring.

What Is a Service?

A service is just a class decorated with @Injectable(). There's nothing magical about it — no base class to extend, no interface to implement. It's an ordinary TypeScript class that Angular knows how to create and share.

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

@Injectable({
  providedIn: 'root'  // available app-wide as a singleton
})
export class LoggerService {
  log(message: string) {
    console.log(`[${new Date().toISOString()}] ${message}`);
  }

  error(message: string, error?: unknown) {
    console.error(`[${new Date().toISOString()}] ${message}`, error);
  }
}

providedIn: 'root' means Angular creates one instance of this service for the entire application. Every component that injects LoggerService gets the same object. This is a singleton — and it's the most common pattern.

Injecting a Service Into a Component

Use constructor injection. Angular looks at the constructor parameters, finds the matching provider, and passes the instance in.

import { Component, OnInit } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
  selector: 'app-dashboard',
  template: `<h1>Dashboard</h1>`
})
export class DashboardComponent implements OnInit {
  constructor(private logger: LoggerService) {}

  ngOnInit() {
    this.logger.log('Dashboard initialized');
  }
}

That's it. No factory function, no new LoggerService(), no service locator. Declare the type in the constructor, and Angular handles the rest.

Modern inject() function

Angular 14+ introduced the inject() function as an alternative to constructor injection:

import { Component, inject, OnInit } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
  selector: 'app-dashboard',
  template: `<h1>Dashboard</h1>`
})
export class DashboardComponent implements OnInit {
  private logger = inject(LoggerService);

  ngOnInit() {
    this.logger.log('Dashboard initialized');
  }
}

Same result, but works in any injection context — useful in functional guards, interceptors, and resolvers.

A Realistic Data Service

Most services wrap HTTP calls and expose Observables. Here's a UserService that follows common Angular patterns:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError, shareReplay } from 'rxjs/operators';

export interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'editor' | 'viewer';
}

@Injectable({ providedIn: 'root' })
export class UserService {
  private apiUrl = '/api/users';

  constructor(private http: HttpClient) {}

  getAll(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl);
  }

  getById(id: number): Observable<User> {
    return this.http.get<User>(`${this.apiUrl}/${id}`);
  }

  create(user: Omit<User, 'id'>): Observable<User> {
    return this.http.post<User>(this.apiUrl, user);
  }

  update(id: number, changes: Partial<User>): Observable<User> {
    return this.http.patch<User>(`${this.apiUrl}/${id}`, changes);
  }

  delete(id: number): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/${id}`);
  }

  getAdmins(): Observable<User[]> {
    return this.getAll().pipe(
      map(users => users.filter(u => u.role === 'admin'))
    );
  }
}

Notice: the service returns Observables, not raw data. The component decides when to subscribe. This keeps the service stateless and reusable.

How Components Use the Service

@Component({
  selector: 'app-user-list',
  template: `
    <div class="toolbar">
      <input [formControl]="searchControl" placeholder="Filter users...">
      <button (click)="refresh()">Refresh</button>
    </div>

    <div *ngIf="loading" class="spinner">Loading...</div>

    <table *ngIf="!loading">
      <tr *ngFor="let user of filteredUsers">
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
        <td>{{ user.role }}</td>
        <td>
          <button (click)="deleteUser(user.id)">Delete</button>
        </td>
      </tr>
    </table>
  `
})
export class UserListComponent implements OnInit, OnDestroy {
  users: User[] = [];
  filteredUsers: User[] = [];
  loading = false;
  searchControl = new FormControl('');
  private destroy$ = new Subject<void>();

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.loadUsers();

    // React to search input
    this.searchControl.valueChanges.pipe(
      debounceTime(200),
      takeUntil(this.destroy$)
    ).subscribe(term => {
      this.filteredUsers = this.users.filter(u =>
        u.name.toLowerCase().includes(term.toLowerCase())
      );
    });
  }

  loadUsers() {
    this.loading = true;
    this.userService.getAll().subscribe({
      next: users => {
        this.users = users;
        this.filteredUsers = users;
        this.loading = false;
      },
      error: err => {
        console.error('Failed to load users:', err);
        this.loading = false;
      }
    });
  }

  deleteUser(id: number) {
    this.userService.delete(id).subscribe({
      next: () => this.loadUsers(),  // refresh the list
      error: err => console.error('Delete failed:', err)
    });
  }

  refresh() {
    this.loadUsers();
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

The component is a thin coordination layer. It tells the service what to fetch, pipes the result into the template, and handles user interactions. The actual HTTP logic, URL construction, and data shaping live in the service.

Services Injecting Other Services

Services can depend on each other. Angular resolves the dependency tree automatically.

@Injectable({ providedIn: 'root' })
export class AuthService {
  private currentUser$ = new BehaviorSubject<User | null>(null);

  constructor(private http: HttpClient) {}

  login(credentials: { email: string; password: string }): Observable<User> {
    return this.http.post<User>('/api/auth/login', credentials).pipe(
      tap(user => this.currentUser$.next(user))
    );
  }

  logout(): void {
    this.currentUser$.next(null);
  }

  getCurrentUser(): Observable<User | null> {
    return this.currentUser$.asObservable();
  }

  isLoggedIn(): Observable<boolean> {
    return this.currentUser$.pipe(map(user => user !== null));
  }
}

@Injectable({ providedIn: 'root' })
export class OrderService {
  constructor(
    private http: HttpClient,
    private auth: AuthService  // inject another service
  ) {}

  getMyOrders(): Observable<Order[]> {
    return this.auth.getCurrentUser().pipe(
      filter((user): user is User => user !== null),
      switchMap(user =>
        this.http.get<Order[]>(`/api/users/${user.id}/orders`)
      )
    );
  }
}

OrderService depends on AuthService. Angular creates AuthService first (if it doesn't exist yet), then injects it into OrderService. Both are singletons — the AuthService instance shared across the app is the same one OrderService uses.

Injection Scopes: root vs. Component vs. Module

Where you provide a service determines its lifetime and sharing scope.

providedIn: 'root' — App-wide singleton (default)

@Injectable({ providedIn: 'root' })
export class UserService { }

One instance for the entire app. Created lazily when first injected. Tree-shakeable — if nothing injects it, it's excluded from the bundle.

Component-level — Instance per component

@Component({
  selector: 'app-editor',
  providers: [EditorStateService],  // each editor gets its own instance
  template: `...`
})
export class EditorComponent {
  constructor(private state: EditorStateService) {}
}

Each EditorComponent gets a fresh EditorStateService. When the component is destroyed, the service instance is garbage collected. Use this for component-local state that shouldn't leak between instances.

Module-level — Scoped to a lazy-loaded module

@NgModule({
  providers: [AdminService]  // only exists within this module's injector
})
export class AdminModule { }

If AdminModule is lazy-loaded, AdminService is a separate singleton scoped to that module. Components outside the module can't see it.

When to use which scope

Use providedIn: 'root' for 90% of services. Use component-level providers when you need per-instance state (e.g., a form builder, undo/redo stack). Use module-level providers when you need a singleton scoped to a feature boundary.

Root Injector UserService · AuthService · HttpClient AppModule (eagerly loaded) AdminModule (lazy-loaded) · AdminService DashboardCmp injects UserService EditorCmp providers: [EditorState] AdminCmp injects AdminService EditorState instance A EditorState instance B UserService: shared singleton | EditorState: one per component | AdminService: scoped to lazy module

Stateful Services with BehaviorSubject

Many services need to hold state — the current user, a list of items, filter settings. The pattern is: private BehaviorSubject, public Observable, and methods to update the state.

@Injectable({ providedIn: 'root' })
export class CartService {
  private items$ = new BehaviorSubject<CartItem[]>([]);

  // Public read-only stream
  readonly cartItems$ = this.items$.asObservable();
  readonly itemCount$ = this.items$.pipe(
    map(items => items.reduce((sum, item) => sum + item.quantity, 0))
  );
  readonly total$ = this.items$.pipe(
    map(items => items.reduce((sum, item) => sum + item.price * item.quantity, 0))
  );

  addItem(product: Product, quantity = 1): void {
    const current = this.items$.getValue();
    const existing = current.find(item => item.productId === product.id);

    if (existing) {
      this.items$.next(
        current.map(item =>
          item.productId === product.id
            ? { ...item, quantity: item.quantity + quantity }
            : item
        )
      );
    } else {
      this.items$.next([
        ...current,
        { productId: product.id, name: product.name, price: product.price, quantity }
      ]);
    }
  }

  removeItem(productId: number): void {
    const current = this.items$.getValue();
    this.items$.next(current.filter(item => item.productId !== productId));
  }

  clear(): void {
    this.items$.next([]);
  }
}

Any component that injects CartService gets a live, reactive view of the cart:

@Component({
  selector: 'app-cart-icon',
  template: `
    <span class="badge">{{ count$ | async }}</span>
  `
})
export class CartIconComponent {
  count$ = inject(CartService).itemCount$;
}

@Component({
  selector: 'app-cart-page',
  template: `
    <div *ngFor="let item of items$ | async">
      {{ item.name }} x{{ item.quantity }} — {{ item.price * item.quantity | currency }}
      <button (click)="remove(item.productId)">Remove</button>
    </div>
    <p>Total: {{ total$ | async | currency }}</p>
    <button (click)="clearCart()">Clear Cart</button>
  `
})
export class CartPageComponent {
  private cart = inject(CartService);
  items$ = this.cart.cartItems$;
  total$ = this.cart.total$;

  remove(id: number) { this.cart.removeItem(id); }
  clearCart() { this.cart.clear(); }
}

Both components react to the same data. Add an item from a product page, and the cart icon updates instantly — no manual event wiring, no shared parent component, no @Input/@Output chains.

CartService BehaviorSubject<CartItem[]> cartItems$ · itemCount$ · total$ ProductPageCmp addItem(product) addItem() CheckoutCmp removeItem() · clear() remove() CartIconCmp count$ | async itemCount$ CartPageCmp items$ · total$ | async cartItems$ Components write via methods (top) · components read via Observables (bottom)

Service Communication Patterns

Pattern 1: Event bus between unrelated components

@Injectable({ providedIn: 'root' })
export class EventBusService {
  private events$ = new Subject<AppEvent>();

  emit(event: AppEvent): void {
    this.events$.next(event);
  }

  on<T extends AppEvent['type']>(type: T): Observable<Extract<AppEvent, { type: T }>> {
    return this.events$.pipe(
      filter((event): event is Extract<AppEvent, { type: T }> => event.type === type)
    );
  }
}

// In a deeply nested component:
this.eventBus.emit({ type: 'ITEM_SAVED', payload: item });

// In a completely unrelated component:
this.eventBus.on('ITEM_SAVED').pipe(
  takeUntil(this.destroy$)
).subscribe(event => {
  this.refreshList();
});

Pattern 2: Facade service that coordinates multiple data services

@Injectable({ providedIn: 'root' })
export class DashboardFacade {
  constructor(
    private users: UserService,
    private orders: OrderService,
    private analytics: AnalyticsService
  ) {}

  getDashboardData(): Observable<DashboardData> {
    return forkJoin({
      recentUsers: this.users.getRecent(5),
      pendingOrders: this.orders.getPending(),
      stats: this.analytics.getSummary()
    });
  }
}

// The component only knows about one service:
@Component({ /* ... */ })
export class DashboardComponent implements OnInit {
  data$: Observable<DashboardData>;

  constructor(private facade: DashboardFacade) {}

  ngOnInit() {
    this.data$ = this.facade.getDashboardData();
  }
}

The facade hides the complexity of coordinating three services. The component doesn't know or care that the data comes from three different API endpoints.

DashboardComponent knows only the facade DashboardFacade forkJoin + shareReplay UserService GET /api/users/recent OrderService GET /api/orders/pending AnalyticsService GET /api/analytics

Testing Services

Services are plain classes, making them straightforward to test:

describe('CartService', () => {
  let service: CartService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(CartService);
  });

  it('should start with an empty cart', (done) => {
    service.cartItems$.subscribe(items => {
      expect(items).toEqual([]);
      done();
    });
  });

  it('should add items', (done) => {
    const product: Product = { id: 1, name: 'Widget', price: 9.99 };
    service.addItem(product, 2);

    service.cartItems$.subscribe(items => {
      expect(items.length).toBe(1);
      expect(items[0].quantity).toBe(2);
      done();
    });
  });

  it('should merge duplicate items', (done) => {
    const product: Product = { id: 1, name: 'Widget', price: 9.99 };
    service.addItem(product, 1);
    service.addItem(product, 3);

    service.cartItems$.subscribe(items => {
      expect(items.length).toBe(1);
      expect(items[0].quantity).toBe(4);
      done();
    });
  });
});

For services that depend on HttpClient, use Angular's HttpClientTestingModule:

describe('UserService', () => {
  let service: UserService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    service = TestBed.inject(UserService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('should fetch all users', () => {
    const mockUsers: User[] = [
      { id: 1, name: 'Alice', email: '[email protected]', role: 'admin' }
    ];

    service.getAll().subscribe(users => {
      expect(users).toEqual(mockUsers);
    });

    const req = httpMock.expectOne('/api/users');
    expect(req.request.method).toBe('GET');
    req.flush(mockUsers);
  });

  afterEach(() => httpMock.verify());
});

What's Next

Services hold state with BehaviorSubject, but as your app grows, state management gets more complex. The next article covers reactive patterns in Angular — Subjects, the async pipe, OnPush change detection, and how to structure fully reactive components.