# Dependency Injection — Angular

Source: https://www.geekswithgeeks.com/en/angular/ng-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.

```typescript
@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.

```typescript
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.
