π Services & Dependency Injection
Injectable services, Dependency Injection (DI) hierarchy, providedIn, and RxJS state management.
What is a Service in Angular?
Services are singleton objects that encapsulate business logic, data fetching, or cross-component state management, keeping components lean and focused purely on view presentation.
Creating an Injectable Service
Decorate service classes with `@Injectable({ providedIn: 'root' })` to make them injectable throughout the application.
user.service.ts
TypeScript
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserService { private userSubject = new BehaviorSubject<string | null>(null); user$: Observable<string | null> = this.userSubject.asObservable(); setUser(username: string) { this.userSubject.next(username); } }
Constructor Injection
Inject services directly into component constructors or use the modern `inject()` function.
user-profile.component.ts
TypeScript
import { Component, inject } from '@angular/core'; import { UserService } from './user.service'; @Component({ selector: 'app-user-profile', template: `<p>User: {{ userService.user$ | async }}</p>` }) export class UserProfileComponent { // Modern inject() API (Angular 14+) public userService = inject(UserService); }
Hierarchical Dependency Injection
Angular DI is hierarchical. Providers declared at Root level are singletons across the app, while providers specified at Component level spawn fresh service instances per component instance.
| Provider Level | Scope | Use Case |
|---|---|---|
| providedIn: 'root' | Application-wide Singleton | Global state, HTTP API services, Auth. |
| @Component({ providers: [...] }) | Component & Children Scope | Isolated component instance state. |
| NgModule providers | Module Scope | Shared feature module services. |