Lesson 13 / 30
Dependency Injection
Two ways to get a service instance into a component.
Constructor injection
Declaring a typed parameter in the constructor is the classic way Angular's injector supplies a service.
@Component({ selector: 'app-cart', standalone: true, template: `...` })
export class CartComponent {
constructor(private cartService: CartService) {}
items = this.cartService.getItems();
}The inject() function
inject() gets a dependency without a constructor parameter — handy for field initializers and functional guards.
import { Component, inject } from '@angular/core';
@Component({ selector: 'app-cart', standalone: true, template: `...` })
export class CartComponent {
private cartService = inject(CartService);
items = this.cartService.getItems();
}Why DI matters
Dependency injection makes components easier to test — swap in a fake service instead of the real one during unit tests.