Sub topic 3
Creating a Service with @Injectable
This chapter assumes you know TypeScript classes and decorators, can build a standalone component, and have read the previous chapter on how dependency injection works. You will learn what the @Injectable decorator does, what providedIn: 'root' means, and why this form is the default way to write a service in modern Angular. Injecting the service with inject() or a constructor gets only a brief mention here, because the next chapter covers it in detail.
What @Injectable Does
@Injectable is a class decorator that marks a class as something Angular's dependency injection (DI) system can create. When the Angular compiler sees the decorator, it adds two static members to the class:
| Generated member | Purpose |
|---|---|
| A factory function (`ɵfac`) | Knows how to call `new` on the class and supply its constructor dependencies |
| An injectable definition (`ɵprov`) | Holds the factory, plus where the service is provided when you set `providedIn` |
You never write or call these members yourself. They are the reason a decorator with no arguments still matters. Without @Injectable, the compiler has no record of the class's constructor parameters, so DI cannot build it if the constructor takes dependencies.
The decorator accepts an optional options object. The providedIn option is the one you will use almost every time:
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]);
}
}This service holds a private signal of cart items. It exposes a read-only count derived from that signal, plus one method to change the state. Components never touch items directly. They go through the service's public API.
What providedIn: 'root' Means
providedIn: 'root' tells Angular to register the service with the application's root environment injector. The root environment injector is the top-level injector that bootstrapApplication creates. Registering there has three effects.
- One instance for the whole application. Every consumer that asks for
CartServicegets the same object. This is what lets two unrelated components share cart state. - Lazy creation. Angular does not build the instance at startup. It runs the factory the first time something injects the service, then caches the result.
- Tree-shaking. The registration lives on the service class itself, not in a list somewhere else. If no code in the app imports
CartService, the bundler can drop the class from the build.
The third point is why providedIn: 'root' beats listing the class in a providers array for most services. A providers array references the class directly, so the bundler must keep it even if nothing injects it. The chapter on registering providers covers when you still want that form.
Generating a Service with the CLI
The Angular CLI scaffolds a service for you:
ng generate service cartThe generated class is already decorated with @Injectable({ providedIn: 'root' }) and comes with a spec file. Its output follows the same pattern as CartService above, so you can start adding state and methods right away.
Services That Depend on Other Services
A service can inject other services in exactly the way a component does. Here CartService saves the cart through a small storage service. Both services are root-provided, and Angular resolves the chain for you.
import { Injectable, computed, inject, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class StorageService {
read(key: string): string | null {
return localStorage.getItem(key);
}
write(key: string, value: string): void {
localStorage.setItem(key, value);
}
}
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly storage = inject(StorageService);
private readonly items = signal<string[]>(
JSON.parse(this.storage.read('cart') ?? '[]')
);
readonly count = computed(() => this.items().length);
add(item: string): void {
this.items.update(list => [...list, item]);
this.storage.write('cart', JSON.stringify(this.items()));
}
}The first time a component injects CartService, Angular runs CartService's factory. During construction, inject(StorageService) asks the same root injector for StorageService, which gets created and cached first. After that, both instances live for the lifetime of the application.
Proving the Singleton
You can check that a root service is shared by injecting it in two separate components:
import { Component, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { CartService } from './cart.service';
@Component({
selector: 'app-add-button',
standalone: true,
template: `<button (click)="cart.add('book')">Add book</button>`
})
export class AddButtonComponent {
protected readonly cart = inject(CartService);
}
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.count() }}`
})
export class CartBadgeComponent {
protected readonly cart = inject(CartService);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [AddButtonComponent, CartBadgeComponent],
template: `<app-add-button /> <app-cart-badge />`
})
export class AppComponent {}
bootstrapApplication(AppComponent);Clicking the button updates the badge. Neither component references the other. They only share the one CartService instance held by the root injector.
Other providedIn Values
providedIn accepts more than 'root'. Use the others only when you have a specific reason.
| Value | Effect | Status |
|---|---|---|
| `'root'` | One instance in the application's root environment injector | Recommended default |
| `'platform'` | One instance in the platform injector, shared by every Angular app on the page | Rare. Useful for micro-frontends that bootstrap several apps |
| `'any'` | One instance per lazy-loaded environment injector | Deprecated |
| An NgModule class | Provided only when that module is imported | Deprecated |
| Omitted | Not registered anywhere. You must list it in some `providers` array | Common for component-scoped services |
Leaving out providedIn is a deliberate choice. The FormDraftService used later in this tutorial has a bare @Injectable() because each editor component provides its own copy. When the class carries no providedIn, the developer has to decide where it is provided.
Can You Skip the Decorator?
Strictly speaking, a class without @Injectable can sometimes still be injected. If you list it in a providers array and its constructor takes no parameters, Angular falls back to calling new on it. Fields that use inject() also work in that case, because inject() reads from the current injector at runtime rather than relying on compiler metadata.
Relying on this fallback is fragile, though:
- Adding a constructor parameter later breaks the class with
NG0204: Can't resolve all parameters. - A class without the decorator cannot use
providedIn, so it is never tree-shakable. - Readers lose the visual cue that the class is meant to be managed by DI.
Decorate every service.
Common Errors
| Error | Typical cause | Fix |
|---|---|---|
| `NG0201: No provider for CartService found` (shown as `NullInjectorError`) | The class has `@Injectable()` with no `providedIn` and no `providers` entry | Add `providedIn: 'root'`, or provide it where it is needed |
| `NG0204: Can't resolve all parameters` | Constructor parameters on a class missing `@Injectable` | Add the decorator |
| `NG0200: Circular dependency in DI detected` | Service A injects B and B injects A during construction | Extract the shared logic into a third service, or defer one lookup |
| Two components see different state | The service is root-provided and also listed in a component's `providers`, which creates a second instance | Remove the extra `providers` entry if you want one shared instance |
The last error trips up many developers. providedIn: 'root' does not stop other injectors from providing the same class. A providers entry closer to the consumer wins. The chapters on the injector hierarchy and component scoping explain exactly how Angular decides.
Edge Cases Worth Knowing
- Lazy-loaded routes. A root-provided service used only by a lazy route still ends up as a single app-wide instance. The bundler moves its code into the lazy chunk, so it does not load up front.
- Service lifetime. A root service lives until the application is destroyed. Clean up timers or subscriptions in
ngOnDestroyon the service, or withinject(DestroyRef).onDestroy(...). Angular calls these when the root injector is torn down, for example in tests or when the app is unmounted. - Constructor side effects. Lazy creation means a service's constructor runs at the first injection, which may happen in the middle of rendering. Avoid heavy synchronous work or network calls in the constructor.
- Server-side rendering. The root injector is created per request on the server, so a root service is a singleton per request there, not across users. Do not store per-user data in module-level variables outside the class.
Exercise
You write @Injectable() export class AuditService {} and inject it in a component with inject(AuditService). No providers array lists it. What happens, and what is the smallest change that fixes it while keeping the service tree-shakable?
Show answer
Angular throws NG0201 (NullInjectorError: No provider for AuditService) because a bare @Injectable() does not register the class with any injector. Change the decorator to @Injectable({ providedIn: 'root' }). This registers the class on itself, so the bundler can still drop it if nothing imports it.
Exercise
CartService is declared with providedIn: 'root'. A developer also adds CartService to the providers array of a CheckoutComponent. The header badge and the checkout page now show different item counts. Explain why.
Show answer
The CheckoutComponent's providers entry creates a second CartService instance in that component's element injector. CheckoutComponent and its children resolve CartService from the nearer injector and get that new instance. The header badge sits outside that subtree and still gets the root instance. The two instances hold separate signals, so their counts diverge. Removing the providers entry restores a single shared instance.
Exercise
In the CartService that depends on StorageService, why must the storage field be declared before the items field?
Show answer
Class field initializers run top to bottom. The items initializer calls this.storage.read(...), so storage must already be assigned. If items came first, this.storage would be undefined at that point and construction would throw a TypeError.