Sub topic 3
Creating a Service with @Injectable
This chapter assumes you know TypeScript classes and generics, can build a standalone component, and have seen bootstrapApplication. Signals appear in the example, but you only need to know that signal() holds a value and computed() derives one from it.
The previous chapter described the injector as a container that creates objects and hands them out. This chapter shows how to write a class the injector can create, and how to register it so the whole application shares one instance.
The minimal service
A service is an ordinary TypeScript class with the @Injectable decorator. The Angular CLI generates one for you:
ng generate service cartThat command writes cart.service.ts. Here is a version that holds cart state:
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly items = signal<string[]>([]);
readonly count = computed(() => this.items().length);
add(item: string): void {
this.items.update(list => [...list, item]);
}
}The class body has nothing Angular-specific except the signals. The decorator does the DI work.
What @Injectable actually does
@Injectable tells the Angular compiler to generate a factory for the class. A factory is a function the injector calls to build an instance. The factory also resolves the class's own dependencies, whether you declare them as constructor parameters or with inject() in field initializers. Chapter 4 covers both forms.
The providedIn option goes one step further. It registers the class with an injector, so you don't have to list it in any providers array.
| Option | Effect |
|---|---|
| `@Injectable()` | Factory generated; you must register it in a `providers` array yourself |
| `@Injectable({ providedIn: 'root' })` | Registered in the root environment injector; one instance for the app |
| `@Injectable({ providedIn: 'platform' })` | Shared by every Angular app on the page; rarely needed |
Use providedIn: 'root' as your default for application-wide services.
Why 'root' is tree-shakable
Tree shaking means the bundler removes code that nothing imports. With providedIn: 'root', the service declares where it belongs, and nothing else points at it. If no component or service ever injects CartService, the build drops it.
If you instead list the service in bootstrapApplication's providers array, that array imports the class. The bundler sees the import and keeps the service in the bundle even when nobody uses it.
The root injector also creates the instance lazily. Nothing is constructed until the first consumer asks for it, and every later consumer gets that same instance.
Common errors
NullInjectorError: No provider for CartService!happens when you used@Injectable()withoutprovidedInand never registered the class anywhere. AddprovidedIn: 'root'or register a provider.NG0202(constructor not compatible with DI) happens when a class has constructor parameters but no@Injectable. Angular has no generated factory, so it cannot tell what to pass. Add the decorator.- Unexpected multiple instances happen when a class is both
providedIn: 'root'and listed in a component'sproviders. The component gets a separate instance. Remove the duplicate registration unless you want that. - Calling
new CartService()yourself gives you an object outside DI. Its state is separate from the shared instance, and tests cannot replace it.
Exercise
You write @Injectable() export class AuditService {} and inject it in a component, and the app throws NullInjectorError. Give two fixes, and say which one keeps the service tree-shakable.
Show answer
Change the decorator to @Injectable({ providedIn: 'root' }), or add AuditService to a providers array (for example in bootstrapApplication or a component). Only providedIn: 'root' is tree-shakable, because no providers array imports the class.
Exercise
Two components each inject CartService, which uses providedIn: 'root'. One calls add('book'). What does the other component's count() return, and why?
Show answer
It returns 1. The root injector creates a single instance on first injection and gives that same instance to every consumer, so both components read the same items signal.